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

筅森魡賤 提交于 2019-12-04 10:03:18

问题


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, ?????
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.


回答1:


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



来源:https://stackoverflow.com/questions/6852142/ruby-rails-can-i-use-a-joined-tables-scopeor-class-method-as-part-of-my-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!