2012-12-05 29 views
0

我已經擴展了很多has_many聲明來過濾/加入/預加載關聯。我想在我聲明has_many時重新使用這些擴展中的一部分:通過關係。這可能嗎?我應該採取不同的方法嗎?我可以在has_many:through聲明中使用擴展的活動記錄關聯嗎?

例子:

我在圖書館型號有這樣的:

class Library < ActiveRecord::Base 
    has_many :meals, :dependent => :destroy do 
    def enabled 
     where(:enabled => true) 
    end 
    end 
end 

我一頓模型具有這樣的:

class Meal < ActiveRecord::Base 
    has_many :servings, :inverse_of => :meal, :dependent => :destroy 
end 

我想我的圖書館有很多份,但只能從啓用的膳食中獲得。有幾個方法,我可以這樣做:

# repeat the condition in the has_many :servings declaration 
class Library < ActiveRecord::Base 
    has_many :servings, :through => :meals, :conditions => ["meals.enabled = ?", true] 
end 

# declare a different meals association for only the enabled meals 
class Library < ActiveRecord::Base 
    has_many :enabled_meals, :class_name => "Meals", :conditions => [:enabled => true] 
    has_many :servings, :through => :enabled_meals 
end 

有什麼辦法來重新使用擴展到現有的:餐宣言?(def在第一個代碼塊中啓用)

回答

0

看起來很像您想要使用activerecord-association-extensions,如http://blog.zerosum.org/2007/2/8/activerecord-association-extensions.html中所述。

我還沒有嘗試過,但我認爲你可以這樣做:

module LibraryMealExtensions 
    def enabled? 
    where(:enabled=>true) 
    end 

    def standard_includes 
    includes(:servings) 
    end 
end 

class Library < ActiveRecord::Base 
    has_many :meals, :dependent => :destroy, :extend=>LibraryMealExtensions 
    has_many :servings, :through => :meals, :extend=>LibraryMealExtensions 
end 

不知道的 「啓用=>真正的」 有 - 你可能不得不說

where("meals.enabled=true") 

b/c與別名混淆。

相關問題