2010-10-11 48 views
0

假設一個多態關聯,比如說'商業'和'職員',這兩個關係都是'可居住的'(意味着他們有幾個小時分配給他們)。讓「小時」模型在業務對象或員工對象的小時內執行相同方法的建議方法是什麼?多態關聯共享模型

對於一個簡單的例子,「小時」的模式可能包含:

def self.find_hours_for_id(id) 
    Business.find(id).hours 
    end 

不過,我可能要工作人員在執行相同的方法,在這種情況下,同樣的方法將改爲調用相當於的

Staff.find(id).hours 

是好還是壞的形式爲設置基準模型類中的型號名稱:

class BusinessHour < Hour 
    @mymodel = "Business" 
end 

class Hour < ActiveRecord::Base 
    def self.find_hours_for_id(id) 
    @mymodel.constantize.find(id).hours 
    end 
end 

然後從控制器,請致電:

BusinessHour.find_hours_for_id(id) 

有沒有更好的解決辦法?

回答

1

你也可以像這樣使用一個模塊。

module Hour 
    def hours_by(model) 
    class_eval do 
     def self.find_hours_for_id(id) 
     model.find(id).hours 
     end 
    end 
    end 
end 

class BusinessHour < AR 
    extends Hour 
    hours_by Business 
end 

BusinessHour.find_hours_for_id(id) 
+0

謝謝!你會說這比我做的好嗎?我的解決方案也可以接受嗎?只是好奇。 – 99miles 2010-10-11 18:13:32

+0

您的解決方案是可以接受的。這只是一個不同的方式。我的解決方案效果更好,如果你有「多重」繼承 – shingara 2010-10-11 19:05:34

1

假設,哦例如,你的對象模型是這樣的:

class Business < ActiveRecord::Base 
    has_many :hours, :as => :hourable 
end 

class Staff < ActiveRecord::Base 
    has_many :hours, :as => :hourable 
end 

class Hour < ActiveRecord::Base 
    belongs_to :hourable, :polymorphic => true 
end 

class BusinessHour < Hour 
    # etc 
end 

那麼你已經有了你所需要的類的引用「hourable,」你可以添加如下取景器:

class Hour < ActiveRecord::Base 
    belongs_to :hourable, :polymorphic => true 

    def self.get_hours_by_hourable_id(id) 
    hourable.class.find(id).hours 
    end 
end 

只是一個建議,但你可能會考慮把驗證的子類,以保證:hourable是合適的類型,如:

class BusinessHour < Hour 
    validates :hourable_must_be_business 

    def hourable_must_be_business 
    unless hourable_type == 'Business' 
     self.errors.add_to_base("Hourable for BusinessHour must be Business") 
    end 
    end 
end 
+0

嗯,這就是我的模型看起來像,但是當我嘗試訪問Hour模型中的'hourable'時,我得到:「未定義的局部變量或方法' 「 – 99miles 2010-10-11 17:40:22

+0

Doh。是的,這是一個類實例中的實例調用。我的錯。 Lemme就是這麼做的。 – 2010-10-11 17:57:15

+0

大聲笑...下午計劃會議。我會爲此工作。有趣的問題。初看起來shingara的元模塊解決方案看起來是一個不錯的選擇。 – 2010-10-11 18:02:03