的Ruby / Rails的 - 我可以使用一个连接表的范围(或类的方法)作为我的WHERE子句中的一部分? [英] Ruby / Rails - Can I use a joined table's scope(or class method) as part of my WHERE clause?

查看:122
本文介绍了的Ruby / Rails的 - 我可以使用一个连接表的范围(或类的方法)作为我的WHERE子句中的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想抓住所有包含可购买产品

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

所以,我试图定义:with_purchaseable_products 。这工作:

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

但是,这不是很干。有没有什么办法可以申请我的:可购买范围产品在我的:with_purchaseable_products 范围有多大?

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

感谢。

推荐答案

您应该使用该合并方法

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

了解更多关于<一个href="http://asciicasts.com/episodes/215-advanced-queries-in-rails-3">http://asciicasts.com/episodes/215-advanced-queries-in-rails-3

这篇关于的Ruby / Rails的 - 我可以使用一个连接表的范围(或类的方法)作为我的WHERE子句中的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆