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