2014-11-16 26 views
1

我有一個模型需要在另一個模型中使用以下兩種方法,所以我想我會嘗試通過關注而不是重複代碼來分享它們。嘗試將模型代碼移動到共享關注點

class Region < ActiveRecord::Base 

    def ancestors 
    Region.where("lft < ? AND ? < rgt", lft, rgt) 
    end 

    def parent 
    self.ancestors.order("lft").last 
    end 

end 

我已經創建了應用程序/模型/憂慮/ sets.rb文件和我的新模型上寫着:

class Region < ActiveRecord::Base 
    include Sets 
end 

sets.rb是:

module Sets 
    extend ActiveSupport::Concern 

    def ancestors 
    Region.where("lft < ? AND ? < rgt", lft, rgt) 
    end 

    def parent 
    self.ancestors.order("lft").last 
    end 

    module ClassMethods 

    end 
end 

問題: 當方法參考模型時,如何共享模型之間的方法,如「Region.where ...」

回答

2

要麼通過r eferencing類中包括模型的(但你需要用在included塊的實例方法):

included do 
    def ancestors 
    self.class.where(...) # "self" refers to the including instance 
    end 
end 

或(更好IMO)通過剛剛宣佈的方法,一個類的方法,在這種情況下,你可以離開該類本身完全是:

module ClassMethods 
    def ancestors 
    where(...) 
    end 
end 
+0

在第二種方法中,我如何引用與實例本身相關的變量lft&rgt? – Dercni

+1

你說得對,我不認爲你可以。所以在這種情況下不要使用類方法;如果您不需要爲查詢使用實例變量,請使用類方法方法。優點是它們是可鏈接的,例如, 'Region.ancestors.limit(10)'。 – Thilo