Ruby 你有很多或更多的爱好吗

Ruby 你有很多或更多的爱好吗,ruby,ruby-on-rails-3,Ruby,Ruby On Rails 3,这个问题已经被问了很多次了,但我无法对我的具体情况给出任何答案,所以我来回答 我有一个事件,选项和一个模板表。还有一个名为events\u templates的联接表,其中包含以下字段: 选项\u id 模板id 事件id 一个事件每个选项有一个模板。但是很明显,可以有很多模板,因为有多个选项 目前,我的事件模型具有该方法 有很多:模板,类名:“EventsTemplate” 问题是,这是正确的设置还是我应该使用HABTM 非常感谢 我认为您应该根据您指定的要求将此设置稍微不同 has_ma

这个问题已经被问了很多次了,但我无法对我的具体情况给出任何答案,所以我来回答

我有一个
事件
选项
和一个
模板
表。还有一个名为
events\u templates
的联接表,其中包含以下字段:

  • 选项\u id
  • 模板id
  • 事件id
一个事件每个选项有一个模板。但是很明显,可以有很多模板,因为有多个选项

目前,我的
事件
模型具有该方法

有很多:模板,类名:“EventsTemplate”

问题是,这是正确的设置还是我应该使用HABTM


非常感谢

我认为您应该根据您指定的要求将此设置稍微不同

has_many :templates, class_name: "EventsTemplate"
这不是你想要的方式。它将为事件提供关联模板,但调用该关联将返回EventTemplates

您可能希望使用
关联来设置此设置

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
class EventTemplate
我认为您应该根据您指定的要求将此设置稍微不同

has_many :templates, class_name: "EventsTemplate"
这不是你想要的方式。它将为事件提供关联模板,但调用该关联将返回EventTemplates

您可能希望使用
关联来设置此设置

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
class EventTemplate
谢谢,这正是我提出的解决方案:)现在我可以简单地使用
Event.Event\u templates.option
Event.templates
很高兴看到您的解决方案得到确认:)谢谢,这正是我提出的解决方案:)现在我可以简单地使用
Event.Event\u templates.option
Event.templates
很高兴看到您的解决方案得到确认:)