开发者

Ruby / Rails - Can I use a joined table's scope(or class method) as part of my WHERE clause?

I want to grab all the categories that contain purchaseable products.

class Product < ActiveRecord::Base
  belongs_to :category
  scope :purchaseable, where(:available => true)
end 

class Category < ActiveRecord::Base
  has_many :products
  scope :with_purchaseable_products, ???开发者_StackOverflow??
end

So, I'm trying to define :with_purchaseable_products. This works:

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

But that's not very DRY. Is there any way to apply my :purchaseable scope to products in my :with_purchaseable_products scope?

Thanks.


You should use the merge method

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

Read more on http://asciicasts.com/episodes/215-advanced-queries-in-rails-3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜