【问题标题】:ActiveRecord: Reference attribute from associated model in where statementActiveRecord:where 语句中关联模型的引用属性
【发布时间】:2015-07-02 19:30:45
【问题描述】:

我有两个具有 has_many / has_many 关系的模型。我有一个变量exp_ids,它是一个整数数组,代表一些ExperienceLevel 记录的ID。我需要编写一个查询来选择所有JobDescriptions,这些ExperienceLevel 具有这些ID 之一。

查询必须在名为 job_descriptions 的现有 ActiveRelation 对象上运行,该对象正在通过我的控制器中的一些流控制传递,以根据我的参数过滤结果。

我已经尝试了以下这些查询以及其他一些变体,但收效甚微。据我所知,ActiveRecord 认为 experience_levels 是一个属性,导致它失败。

  • job_descriptions.where(experience_levels: exp_ids)
  • job_descriptions.joins(:experience_levels).where(experience_levels.id: exp_ids)
  • job_descriptions.joins(:experience_levels).where(experience_levels: exp_ids)
  • job_descriptions.joins(:experience_levels).where("experience_levels.id IN exp_ids")
  • job_descriptions.includes(:experience_levels).where("experience_levels.id = ?", exp_ids).references(:experience_levels)

这是我的模型:

class JobDescription < ActiveRecord::Base
    has_many :job_description_experience_levels
    has_many :experience_levels, through: :job_description_experience_levels
end

class JobDescriptionExperienceLevel < ActiveRecord::Base
    belongs_to :job_description
    belongs_to :experience_level
end

class ExperienceLevel < ActiveRecord::Base
    has_many :job_description_experience_levels
    has_many :job_descriptions, through: :job_description_experience_levels
end

我不确定我想做的事是否可行。我对另一个job_description 过滤器使用了类似的方法,在该过滤器中我选择了company_id,但在这种情况下,company_idJobDescription 的一个属性。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    试试这个:

    job_descriptions.joins(:job_description_experience_levels).where(job_description_experience_levels: { experience_level_id: exp_ids })
    

    【讨论】:

      【解决方案2】:

      job_descriptions.joins(:experience_levels).where(experience_levels: {id: exp_ids})

      【讨论】:

      • 这个也很完美。我将 vegetaras 的回复标记为答案,因为它是第一个,但我更喜欢你的回复,因为它更简洁。
      【解决方案3】:

      试试这个。请注意经验级别上缺少复数。id

      job_descriptions.includes(:experience_levels).where("experience_level.id = ?", exp_ids).references(:experience_levels)
      

      【讨论】:

      • 我之前试过这个,在experience_levels.id 上使用复数形式,但没有。两者都不起作用。
      猜你喜欢
      • 1970-01-01
      • 2014-07-01
      • 2014-04-27
      • 2013-07-29
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多