我有一个控制器方法,目前返回一个随机记录。
控制器
@recipe = Recipe.order('RANDOM()').first
它查询的模型通过与另一个表的关联有一个has_many。
我想返回一个基于关联的随机结果。
模型菜谱
class Recipe < ApplicationRecord
attribute :name
has_many :recipe_seasons
has_many :seasons, through: :recipe_seasons
end
赛季
class Season < ApplicationRecord
has_many :recipe_seasons
has_many :recipes, through: :recipe_seasons
end
配方的季节
class RecipeSeason < ApplicationRecord
belongs_to :recipe
belongs_to :season
end
到目前为止
@date = Time.now
@month = @date.month
@season = Season.find(@month)
@recipe = Recipe.where(recipe_seasons: @month).order('RANDOM()').first
这将返回一个食谱,其recipe_season id的值存储在month变量中。我真正想要的是一个食谱从season_id的值存储在变量@month。
做了一个完整的猜测,我试着:
@recipe = Recipe.where(recipe_seasons: season_id: @month).order('RANDOM()').first
我想你要:
@season = Season.find(@month)
@recipe = Recipe.where(season: @season).order('RANDOM()').first