这是我的模型:
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 = Complaint.all.joins(:complaints_problem_area).where(problem_area_id: nil)
最佳答案
你是对的,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
。
关于ruby-on-rails - 查找在丰富的连接表 rails 中没有关联记录的所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33596779/