2013-04-09 75 views
1

這個問題已經被問過很多次了,但是我不能對我的具體情況提出任何答案,所以在這裏。has_many或HABTM

我有一個events,options和一個templates表。還有一個連接表稱爲events_templates與字段:

  • option_id
  • template_id
  • 事項標識

事件都有每個選項一個模板。但顯然可以有很多模板,因爲有多個選項。

目前我event模型方法

has_many :templates, class_name: "EventsTemplate"

的問題是,這是正確的設置或我應該使用HABTM?

非常感謝!

回答

1

我認爲你應該根據你指定的要求設置這個有點不同。

has_many :templates, class_name: "EventsTemplate" 

這不會按照您希望的方式工作。它會給事件一個關聯模板,但調用該關聯將返回EventTemplates。

您可能想要使用through關聯進行設置。

class EventTemplate < ActiveRecord::Base 
    belongs_to :option 
    belongs_to :template 
    belongs_to :event 
end 

class Event 
    has_many :event_templates 
    has_many :templates, through: :event_templates 
end 
+0

謝謝,這正是我想出以及解決方案:)現在我可以簡單地使用'Event.event_templates.option'和'Event.templates' – 2013-04-10 09:07:22

+0

很高興見到您的解決方案證實了:) – Arjan 2013-04-10 09:10:22