2017-01-01 66 views
0

新年快樂給大家!導軌5:「belongs_to的通過」類型的關聯

我有經典has_many through association

class Physician < ApplicationRecord 
    has_many :appointments 
    has_many :patients, through: :appointments 
end 

class Appointment < ApplicationRecord 
    belongs_to :physician 
    belongs_to :patient 
end 

class Patient < ApplicationRecord 
    has_many :appointments 
    has_many :physicians, through: :appointments 
end 

但是現在我需要從class Appointment添加has_many聯想到一些class Example,這與其他模型belongs_to協會將在belongs_to伴隨class Example

如果可能的話,如何設置這種assosiation的?謝謝。

更新

我不明白,爲什麼這個問題是downvoted。 以下是我需要class Example

class Example < ApplicationRecord 
    belongs_to :appointment 
    belongs_to :model_bbb 
end 

更新2

好吧,我想通了,我可以使用解決方案從this answer。基本上我可以刪除「預約」的模式,並有class Example這樣的:

class Example < ApplicationRecord 
    belongs_to :physician 
    belongs_to :patient 
    belongs_to :model_bbb 
end 

然後在醫生和病人,我可以做has_many :examples和另一through關係。我也想做一些奇怪的belongs_to through東西我能有class Appointment相對小桌子,但class Example表預計將相當大。所以我最初的想法是不創建額外的列,這將被重複多次。

+0

問題是不理解。那麼,你最後的片段有什麼問題?順便說一句,請編輯標籤以改善分類 - 因爲這是一個ruby-on-rails-5線程。 – marmeladze

回答

0

你可以只通過你的約會模型類添加的has_many或的has_many。

請記住,belongs_to協會是總是上的表具有外鍵。所以,如果你的建模是正確的,你應該在例子表上有一個appointment_id。

有使用關聯表中與另一個的關係沒有問題。實際上,使用中間表的想法是能夠在其上存儲其他信息(另一方面,你會做HABTM)。

+0

謝謝,請檢查我的上述更新2。目前看來,這對我來說是最有效的解決方案。請評論你是否有其他想法。 – matiss