Ruby / Rails – 我可以使用连接表的范围(或类方法)作为WHERE子句的一部分吗?

我想抓住包含可购买products所有类别。

 class Product  true) end class Category < ActiveRecord::Base has_many :products scope :with_purchaseable_products, ????? end 

所以,我正在尝试定义:with_purchaseable_products 。 这有效:

 scope :with_purchaseable_products, joins(:products).where("products.available is true").group(:id).having('count(products.id) > 0') 

但那不是很干。 有没有办法将我的:purchaseable范围应用于我的:with_purchaseable_products范围?

谢谢。

您应该使用合并方法

 class Category < ActiveRecord::Base has_many :products scope :with_purchaseable_products, joins(:products).merge(Product.purchaseable).group(:id).having('count(products.id) > 0') end 

更多信息,请访问http://asciicasts.com/episodes/215-advanced-queries-in-rails-3