简体   繁体   中英

How to Select a random object from collection on rails?

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?

3limit4t0r was correct.

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

calling this on the view

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

thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM