1

這裏是我的模型:查找具有豐富的內部沒有相關記錄的所有記錄加入臺導軌

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沒有任何關聯problem areas

我認爲解決方案可能有左連接的東西?像這樣的東西(儘管這似乎並沒有工作)

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

回答

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

+0

謝謝!我需要研究一些更多的「左連接」 – Neil

1

您可以構建一個left join查詢用ActiveRecord方法,而不是原始的SQL語句,使用includes

Complaint.includes(:complaints_problem_areas) 
     .where(complaints_problem_areas: {problem_area_id: nil}) 
     .references(:complaints_problem_areas) 
相關問題