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

joh*_*kes 19 activerecord scope ruby-on-rails arel ruby-on-rails-3

我想抓住所有包含可购买的类别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
Run Code Online (Sandbox Code Playgroud)

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

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

但那不是很干.有没有办法将我的:purchaseable范围应用到products我的:with_purchaseable_products范围内?

谢谢.

Fab*_*bio 37

您应该使用合并方法

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

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