简体   繁体   English

如何从轨道上收集 Select 随机 object?

[英]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.我有一部 model class 电影,我被要求在 select 一个随机 ZA8CFDE6331BD59EB2AC96F891ZC4 上显示它作为特色。 This should be a class method这应该是一个 class 方法

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. 3limit4t0r 是正确的。

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

calling this on the view在视图上调用它

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

thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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