【发布时间】:2023-01-10 03:54:20
【问题描述】:
我有一个当前返回随机记录的控制器方法。
控制器
@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 是存储在月份变量中的值。我真正想要的是来自 season_id 的一个食谱,其值存储在变量@month 中。
完全猜测,我试过:
@recipe = Recipe.where(recipe_seasons: season_id: @month).order('RANDOM()').first
【问题讨论】:
标签: ruby-on-rails activerecord associations