[英]Rails condition where association has_many has count more than one
Package.rb Package.rb
has_many :deals
Deal.rb Deal.rb
belongs_to package
Now simple question is I want to get all packages where deals count is more than one. 现在简单的问题是,我想获得所有交易数量大于一个的包裹。 What is the best method to do it? 最好的方法是什么? where(:available_for_purchase => true)
and self.deals.count > 0
where(:available_for_purchase => true)
和self.deals.count > 0
(package.rb) (package.rb)
class << self
def available
where(:available_for_purchase => true)
end
end
def self.available
joins(:deals).where(:available_for_purchase => true).uniq
end
Joining the deals
association will remove Packages
without any deals ... SQL is doing the hard work here. 加入deals
协会将删除没有任何交易的Packages
... SQL在这里做了艰苦的工作。
Then use : 然后使用:
Package.available
I'd use a counter-cache to give you the deal count as a column on the Package model, which will then let you use SQL for conditions. 我将使用计数器缓存将交易计数作为Package模型上的一列提供,然后让您将SQL用于条件。
Package.rb Package.rb
has_many :deals
def with_deals
where("deals_count > 0")
end
Deal.rb Deal.rb
belongs_to :package, :counter_cache => true
Then you can just call: 然后,您可以致电:
Package.with_deals
You can see an example of how to setup counter cache here: http://railscasts.com/episodes/23-counter-cache-column 您可以在此处查看如何设置计数器缓存的示例: http : //railscasts.com/episodes/23-counter-cache-column
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.