2011-09-19 68 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