【发布时间】: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_id 是JobDescription 的一个属性。
【问题讨论】:
标签: ruby-on-rails activerecord