我有两个具有 has_many/has_many 关系的模型。我有一个变量 exp_ids
,它是一个整数数组,表示一些 ExperienceLevel
记录的 id。我需要编写一个查询,该查询将选择具有这些 id 之一的 ExperienceLevel
的所有 JobDescription
。
查询必须在名为 job_descriptions
的现有 ActiveRelation 对象上运行,该对象正在通过我的 Controller 中的一些流程控件传递,以根据我的参数过滤结果。
我尝试了下面的这些查询和其他一些变体,但收效甚微。据我所知,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_id
是 的属性>职位描述
。
最佳答案
试试这个:
job_descriptions.joins(:job_description_experience_levels).where(job_description_experience_levels: { experience_level_id: exp_ids })
关于ruby-on-rails - ActiveRecord:where 语句中关联模型的引用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31193081/