[英]How to Select a random object from collection on rails?
我有一部 model class 電影,我被要求在 select 一個隨機 ZA8CFDE6331BD59EB2AC96F891ZC4 上顯示它作為特色。 這應該是一個 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
我需要在索引上調用它
def index
@movies = Movie.all
end
這是在鐵軌上。 有任何想法嗎?
3limit4t0r 是正確的。
def self.featured
where.not(title: nil).sample
end
在視圖上調用它
<h2>Featured:</h2><%= @movies.featured.title%>
謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.