2011-10-11 65 views
0

我有以下型号:应用范围在加入

class Category < ActiveRecord::Base 
    has_many :items 
    default_scope where(:enabled => true, :out_of_stock => false) 
    scope :enabled, where(:enabled => true) 
    scope :out_of_stock, where(:out_of_stock => true) 
end 

class Item < ActiveRecord:Base 
    belongs_to :category 
end 

我遇到下面的代码重复,重复跨越整个项目范围的条件,使用时加入:

Category.joins(:offers).where(:items => {:merchant_id => @merchant.id, :enabled => true, :out_of_stock => false}) 

这将是很好,如果在连接中应用指定范围将是可能的:

Category.joins(:offers).where(:items => {:merchant_id => @merchant.id, :scope => :default}) 

回答

0

尝试使用& lik e这:

Category.joins(:offers, :items) & Item.default.where(:merchant_id => @merchant.id) 

我认为这被称为插值。它将两个查询结合在一起,保留第一个作为基地(它返回Category对象)。