【问题标题】:Find all records which have no associated records within rich join table rails在富连接表轨道中查找所有没有关联记录的记录
【发布时间】:2015-11-08 17:24:22
【问题描述】:

这是我的模型:

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    

我想获取所有没有关联problem areasComplaints

我认为解决方案可能包含左连接?像这样的东西(虽然这似乎不起作用)

complaints = Complaint.all.joins(:complaints_problem_area).where(problem_area_id: nil)

【问题讨论】:

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


    【解决方案1】:

    你说得对,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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-23
        • 2011-07-16
        • 2011-07-16
        相关资源
        最近更新 更多