7

我有三個型號,每個都具有以下關聯:設置一:的has_many:on Rails的通過一個belongs_to的關聯紅寶石協會

class Model1 < ActiveRecord::Base 
    has_many :model2s 
    has_many :model3s 
end 

class Model2 < ActiveRecord::Base 
    belongs_to :model1 
    has_many :model3s, :through => :model1 # will this work? is there any way around this? 
end 

class Model3 < ActiveRecord::Base 
    belongs_to :model1 
    has_many :model2s, :through => :model1 # will this work? is there any way around this? 
end 

正如你可以在註釋文本看,我剛纔提到我需要什麼。

回答

6

你剛纔創建的方法來訪問它

class Model2 < ActiveRecord::Base 
    belongs_to :model1 

    def model3s 
    model1.model3s 
    end 
end 

或者,您也可以委託給MODEL1的model3s方法

class Model2 < ActiveRecord::Base 
    belongs_to :model1 

    delegate :model3s, :to => :model1 

end 
+0

委託部分給我這個錯誤「委託需要一個目標,提供一個選項散列,其中以:作爲最後一個參數(如:委託:你好,:= =>:greeter)。讓我試試方法部分 – Rohit 2010-10-05 13:45:34

+0

第一種方法是做得很好,並解決我的問題。但請在委託機制中找出一些調整並編輯答案。 :D – Rohit 2010-10-05 13:59:07

+0

使用委託:model3s,:to =>:model1代替委託:model3s,:as =>:model1。 :D適合我 – Rohit 2010-10-05 14:04:14

0

爲什麼不嘗試:

class Model1 < ActiveRecord::Base 
    has_many :model2s 
    has_many :model3s 
end 

class Model2 < ActiveRecord::Base 
belongs_to :model1 
has_many :model3s, :primary_key => :model1_id, 
         :foreign_key => :model1_id 

end 

class Model3 < ActiveRecord::Base 
    belongs_to :model1 
    has_many :model2s, :primary_key => :model1_id, 
         :foreign_key => :model1_id 
end 

這將有有效的記錄通過model1_id加入model2和model3,使model1完全脫離它並且應該更加高效。

+1

In一般情況下,這將失去與Model1中的「has_many」定義相關的任何條件。例如如果Model1是用'has_many:model2s, - > {where deleted:false}定義的,那麼在不編寫一些可能易碎和/或冗長的代碼的情況下,您不會選擇這些條件。只是要注意的事情。 – 2014-04-21 21:15:37