0

三種型號:選擇記錄基於關聯計數(加入?)

class Customer < ActiveRecord::Base 
    has_many :visits 
end 

class Visit < ActiveRecord::Base 
    belongs_to :customer 
    has_many :messages 
end 

class Message < ActiveRecord::Base 
    belong_to :visit 
end 

現在我想返回所有在他們的郵件客戶訪問。所以在僞代碼這樣的事情:

@customer = Customer.find(:id) 
@customer.visits.where(visit has messages) 

我該如何做這樣的事情?

回答

2

做一個inner join:(推薦):

# returns a customer's visits that have at least one message 
@customer.visits.joins(:messages) 

確保處理重複

@customer.visits.joins(:messages).(「distinct(categories.id, categories.name)」) 

可能出現的性能問題,另一種選擇是使用SQL EXISTS條款:

@customer.visits.where("EXISTS (SELECT messages.id FROM messages WHERE messages.visit_id == visits.id)") 

SQL IN

@customer.visits.where("visits.id IN (SELECT messages.visit_id FROM messages)") 

http://guides.rubyonrails.org/active_record_querying.html#using-array-hash-of-named-associations