以下是我的模特:
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
答案 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)