查找富联接表轨道中没有关联记录的所有记录

时间:2015-11-08 17:24:23

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord rails-activerecord

以下是我的模特:

class Complaint < ActiveRecord::Base
  has_many :complaints_problem_areas
  has_many :problem_areas, through: :complaints_problem_areas
end

# rich join table for complaints and problem areas
class ComplaintsProblemArea < ActiveRecord::Base
  belongs_to :complaint
  belongs_to :problem_area
end

class ProblemArea < ActiveRecord::Base
  has_many :complaints_problem_areas
  has_many :complaints, through: :complaints_problem_areas
end    

我想抓住所有没有关联Complaints的{​​{1}}。

我认为解决方案可能有左联接的东西?像这样的东西(尽管这似乎不起作用)

problem areas

2 个答案:

答案 0 :(得分:2)

你是对的,LEFT JOIN应该解决这个问题:

Complaint.
  joins('LEFT JOIN complaints_problem_areas ON complaints.id = complaints_problem_areas.complaint_id').
  where('complaints_problem_areas.problem_area_id IS NULL')

joins(:complaints_problem_area)不起作用,因为它会生成INNER JOIN。你想要一个LEFT JOIN

答案 1 :(得分:1)

您可以使用left join使用ActiveRecord方法而不是原始sql构造includes查询:

Complaint.includes(:complaints_problem_areas)
         .where(complaints_problem_areas: {problem_area_id: nil})
         .references(:complaints_problem_areas)