[英]Rails: Polymorphic association needed for subclasses in STI structure?
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. 我工作的一个业余项目,并有一个抽象的
Event
模型与STI子类Meal
, Outing
, Medication
等Event
父模型具有start_time
, end_time
, description
等。
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. 例如,我希望能够将
Image
类的多个实例附加到任何Event
子类。 I want to be able to attach multiple instances of the Medicine
class to the Medication
entities, multiple instance of Location
to Outing
, etc. 我希望能够将
Medicine
类的多个实例附加到Medication
实体, Location
到Outing
多个实例等。
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.
我考虑多态性的原因是要提供灵活性,以便可以想象将任何不同类型的嵌套资源附加到
Event.
任何子类上Event.
This would allow somebody to attach a medicine of "Vitamin D Supplement" to a Meal
, for example. 例如,这可以使某人将“维生素D补充剂”药物附在
Meal
。
My questions are: 我的问题是:
Event
in the type table? Event
? has_many
relationships? has_many
关系? has_many
vs. polymorphic? has_many
和polymorphic有什么性能优势? (1) Yes. (1)是的。
(2) Yes, depending on how you handle the polymorphism. (2)是的,取决于您处理多态性的方式。 Rails allows for STI (single table inheritance) so all subtypes of event can inherit the has_many relation.
Rails支持STI(单表继承),因此事件的所有子类型都可以继承has_many关系。 The related has_many record can have many subtypes, and all of these will appear as relations when called.
相关的has_many记录可以具有许多子类型,所有这些子类型在调用时都将显示为关系。
(3) has_many can be used in conjunction to polymorphic, they are not mutually exclusive. (3)has_many可以与多态一起使用,它们不是互斥的。
(4) Again, the two are not mutually exclusive. (4)同样,两者不是互斥的。 In fact, polymorphic is needed on your belongs_to relation.
实际上,您的归属关系上需要多态。 Your related record should include a relation_id and relation_type in its table.
您的相关记录应在其表中包含一个lation_id和relation_type。 If you are using STI, for instance, you would do it like this:
例如,如果您使用的是STI,则可以这样做:
class BaseClass < ActiveRecord::Base
has_many :foo
end
class SubClass < BaseClass
# inherits has_many :foo relation from BaseClass
end
class Foo < ActiveRecord::Base
belongs_to :base_class, polymorphic: true
end
class Bar < Foo
# inherits belongs_to :base_class from Foo
end
When calling sub_class-instance.foos, you should get an ActiveRecord relation of all foos, including subtypes. 调用sub_class-instance.foos时,您应该获得所有foo(包括子类型)的ActiveRecord关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.