ActiveRecord从没有关联的关联中查找记录

时间:2015-07-09 15:47:32

标签: sql ruby-on-rails activerecord

我在两个模型和一个连接表之间有一个简单的many-to-many关系。在我的Rails控制器中,我有一个名为job_descriptions的ActiveRecord :: Relation对象,它被初始化为JobDescription.all,然后通过流控制来应用其他where语句。这是我的模特:

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_descriptions编写查询,只选择那些没有experience_level关联的实例。我怎么能这样做?

我尝试了ob_descriptions.includes(:job_descriptions).where(job_description_experience_levels: {job_description_id: nil})job_descriptions.where('id NOT IN (SELECT DISTINCT(job_description_id) FROM job_description_experience_levels)')的各种变体,但没有成功。

我通过调用模型本身的查询(例如JobDescription.where(something))而不是现有的关系对象,能够找到关于此主题的大部分资源。

谢谢!

编辑#1

我设法在madyrockss回答之前自己解决这个问题,但我认为答案比我的解决方案更具语义性。无论如何,这是我的解决方案,以防有人帮助他们。

job_descriptions_with_experience_levels = job_descriptions.joins(:experience_levels)
job_descriptions = job_descriptions - job_descriptions_with_experience_levels

通过查找job_descriptions所有experience_levels,然后从job_descriptions中减去该关系来获取没有任何experience_levels的关系。

1 个答案:

答案 0 :(得分:1)

如果job_description没有任何experience_level,那么job_description表格中的job_description_experience_levels就不会有任何条目。 所以你可以做以下事情:

job_desc_ids_with_exp_level = JobDescriptionExperienceLevel.pluck(:job_description_id).uniq

job_descriptions = job_descriptions.where.not(id: job_desc_ids_with_exp_level)