当超类是子类的 FK 时,在 db 中设置多态关联吗?
使用类表继承,建议子类引用超类而不是反之亦然。通常在 Rails 中,多态关联以相反的方向工作——超类指的是子类。
推荐的
vehicle
.id
car
.vehicle_id # PK instead of using id (identity column)
boat
.vehicle_id
典型 Rails 多态关联
vehicle
.id
.subclass_type
.subclass_id
car
.id
boat
.id
我喜欢推荐方法的一点是我可以消除不匹配的键。也就是说,给定的汽车及其车辆超级共享相同的 id。
在我的特定实例中,我可能会支持多重继承,因此,例如,我可以拥有一辆混合车船车辆。
问题:
您将如何设置 ActiveRecord 关联...
如果一辆车只能有一个子类?
车辆是否可以有多个子类? (我在这里看到的问题是,通过不指定特定的 subclass_type,关联如何知道要命中哪个表。我不认为它们会,因此必须命中所有可能的表。所以也许交集表在这里会有所帮助。 )
这是一个与 ActiveRecord 一起使用的良好设计模式吗?或者它是否足够违背 Rails 的方式以至于我们应该避免它?
Using class table inheritance it is recommended that the subclass refers to the superclass and not the other way around. Normally in Rails polymorphic associations work in the other direction--the super refers to the subclass.
Recommended
vehicle
.id
car
.vehicle_id # PK instead of using id (identity column)
boat
.vehicle_id
Typical Rails polymorphic association
vehicle
.id
.subclass_type
.subclass_id
car
.id
boat
.id
What I like about the recommended approach is that I can do away with having non-matching keys. That is, a given car and its vehicle super share the same id.
In my particular instance, I will potentially support multiple inheritance and so, for example, I could have a hybrid car-boat vehicle.
Questions:
How would you set up the ActiveRecord associations...
If a vehicle could have only one subclass?
If a vehicle could have many subclasses? (The problem I see here is that by not specifying a specific subclass_type how do the associations know which table to hit. I don't guess they would and so would have to hit all possible tables. So maybe an intersection table would help here.)
Is this a good design pattern for use with ActiveRecord or does it buck the Rails way enough that we should avoid it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我选择了最简单的解决方案:使用多态关联(如第二个块所示)。它将具有更好的性能并且更易于维护。
I opted for the simplest solution: using a polymorphic association (as shown in the second block). It will have better performance and be more maintainable.