Ruby on rails 查找富联接表rails中没有关联记录的所有记录

Ruby on rails 查找富联接表rails中没有关联记录的所有记录,ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord,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:

以下是我的模型:

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    

你是对的,一个
左连接应该可以解决这个问题:

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

连接(:投诉\u问题\u区域)
不起作用,因为它会生成一个
内部连接。您需要
左连接

您可以使用ActiveRecord方法而不是原始sql,使用
包含
,构造
左连接
查询:

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