1

I have a model class movie and I was asked to select one random object to show it as featured on the index. This should be a class method

class Movie < ApplicationRecord
  belongs_to :user
  has_many :reviews, dependent: :destroy
  has_many :users, through: :reviews
  validates :description, :movie_length, :director, :rating, presence: true
  validates :title, presence: true , uniqueness: true
  
  def self.most_recent
    order('created_at DESC')
  end

  #randondly select a movie onject to disply that on the page.

  def self.featured 
    self.where('title').sample
  end
  
end

And I need to call this on index

    def index
      @movies = Movie.all
    end

This is on rails. any ideas?

Jose Reyes
  • 55
  • 7
  • 1
    Do you mean `@movies = Movie.featured`? There are a few 3 problems with the method though. 1. `where('title')` is not valid, the arguments should be key/value-pairs (for example `where.not(title: nil)`) 2. Don't use `self.where` but just `where`, by calling `where` with `self` as receiver you explicitly call it upon the class, not the active scope, basically just tossing the current scope. 3. By using `sample` you will load all records, then randomly select 1, this is if you have only 100 records but quickly becomes undesirable. See [Random record in ActiveRecord](/q/2752231/3982562) – 3limin4t0r Nov 25 '20 at 23:19
  • ^ Passing a string as argument is technically valid, but the string as currently passed is not really a valid WHERE expression. Rails 6 also does away with passing raw SQL, you now have to wrap SQL strings with `Arel.sql`. – 3limin4t0r Nov 25 '20 at 23:25
  • Does this answer your question? [Random record in ActiveRecord](https://stackoverflow.com/questions/2752231/random-record-in-activerecord) – Schwern Nov 25 '20 at 23:45

1 Answers1

1

3limit4t0r was correct.

def self.featured 
    where.not(title: nil).sample
  end

calling this on the view

<h2>Featured:</h2><%= @movies.featured.title%>

thanks.

Jose Reyes
  • 55
  • 7