【问题标题】:Return random record from a has many through association in rails controller从一个有很多通过 rails 控制器中的关联返回随机记录
【发布时间】: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


    【解决方案1】:

    我想你想要:

    @season = Season.find(@month)
    
    @recipe =  Recipe.where(season: @season).order('RANDOM()').first
    

    【讨论】:

      猜你喜欢
      • 2011-07-13
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 2013-02-24
      相关资源
      最近更新 更多