Rails:STI 结构中的子类需要多态关联吗?
我正在从事一个业余爱好项目,并且有一个抽象的 Event
模型,其中包含 STI 子类 Meal
、Outing
、Memination
等。 Event
父模型有 start_time
、end_time
、description
等。
我想要嵌套资源对于各个子类。例如,我希望能够将 Image
类的多个实例附加到任何 Event
子类。我希望能够将 Medicine
类的多个实例附加到 Meduction
实体,将 Location
的多个实例附加到 Outing
的原因是为了提供灵活性,以便可以想象,任何不同类型的嵌套资源都可以附加到 Event 的任何子类。
这将允许某人附有“维生素D”的药物例如,膳食
的补充品。
我的问题是:
- 嵌套资源应该是多态的吗?
- 如果我将它们设为多态,所有实例是否都会在类型表中包含
Event
? - 如果是这样,我应该让它们成为
has_many
关系吗? - 与多态相比,使它们具有
has_many
是否有任何性能优势?
I'm working on a hobby project and have an abstract Event
model with STI subclasses Meal
, Outing
, Medication
, etc. The Event
parent model has start_time
, end_time
, description
, etc.
I want to have nested resources for the various subclasses. For example, I want to be able to attach multiple instances of the Image
class to any Event
subclass. I want to be able to attach multiple instances of the Medicine
class to the Medication
entities, multiple instance of Location
to Outing
, etc.
My reason for considering polymorphism is to provide flexibility so that, conceivably, any of the different types of nested resources could be attached to any of the subclasses of Event.
This would allow somebody to attach a medicine of "Vitamin D Supplement" to a Meal
, for example.
My questions are:
- Should the nested resources be polymorphic?
- If I make them polymorphic, will all of the instances contain
Event
in the type table? - If so, should I just make them
has_many
relationships? - Is there any performance advantage to making them
has_many
vs. polymorphic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(1) 是的。
(2) 是的,取决于你如何处理多态性。 Rails 允许 STI(单表继承),因此事件的所有子类型都可以继承 has_many 关系。相关的 has_many 记录可以有许多子类型,所有这些子类型在调用时都会显示为关系。
(3) has_many可以和polymorphic结合使用,它们并不互相排斥。
(4) 同样,两者并不相互排斥。事实上,belongs_to 关系需要多态。您的相关记录应在其表中包含relation_id 和relation_type。例如,如果您使用 STI,您可以这样做:
当调用 sub_class-instance.foos 时,您应该获得所有 foo(包括子类型)的 ActiveRecord 关系。
(1) Yes.
(2) Yes, depending on how you handle the polymorphism. Rails allows for STI (single table inheritance) so all subtypes of event can inherit the has_many relation. The related has_many record can have many subtypes, and all of these will appear as relations when called.
(3) has_many can be used in conjunction to polymorphic, they are not mutually exclusive.
(4) Again, the two are not mutually exclusive. In fact, polymorphic is needed on your belongs_to relation. Your related record should include a relation_id and relation_type in its table. If you are using STI, for instance, you would do it like this:
When calling sub_class-instance.foos, you should get an ActiveRecord relation of all foos, including subtypes.