2011-09-19 45 views
2

这是我的联想和范围设置:如何在活动记录中加入has_many与范围的关联?

has_many :owned_products 

has_many :owned_lessons, :through => :owned_products, :source => :lesson, :conditions => "owned_products.product_type = 'Lesson'" 

scope :active_purchase_scope, lambda { 
    where('owned_products.created_at' => (Date.today - CONFIG['downloads']['time_window'].days)..(Date.today)).order('owned_products.created_at DESC') 
} 

def active_lessons 
    owned_lessons.active_purchase_scope 
end 

这是错误我得到:

ruby-1.8.7-p334 :005 > User.find_by_username('joeblow').active_lessons 
NoMethodError: undefined method `active_purchase_scope' for #<User:0x1051a26c8> 

回答

4

一个scope可以被看作是一个类的方法和association可作为实例方法处理。在您的代码示例中,owned_lessons方法返回一个数组对象。您不能在数组对象(或用户对象)上调用active_purchase_scope,因为范围只能在Model类上调用(即您的情况为User.active_purchase_scope

您可以通过在范围上添加范围来解决此问题该Lesson模型

class Lesson 
    has_many :owned_products 

    scope :active_purchase_scope, lambda { 
    include(::owned_products).where('owned_products.created_at' => 
      (Date.today - CONFIG['downloads']['time_window'].days)..(Date.today)). 
      order('owned_products.created_at DESC') 
    } 

end 

并改写User类如下:

class User 

    has_many :owned_products 

    has_many :owned_lessons, :through => :owned_products, :source => :lesson, 
       :conditions => "owned_products.product_type = 'Lesson'" 


    def active_lessons 
    owned_lessons.active_purchase_scope 
    end 

end 

owned_lessons返回上Lesson模型匿名的范围,因此我们可以用S IT连锁从相同的模型应付active_purchase_scope

+0

我明白为什么这不起作用(因为Array类),但我仍然不知道如何抽象active_purchase_scope,因为所有产品都需要使用这个,而不仅仅是Lesson。目前,我的产品型号不能继承任何东西。我是否应该尝试制作一个所有产品都继承的产品模型(这可能会让事情混淆不清,因为我在连接表中有product_id),还是我可以通过mixin完成相同的事情? – pixelearth

相关问题