何时多态不可取?

时间:2014-07-19 08:09:05

标签: ruby-on-rails activerecord

我将提供三种方案,以及我如何在没有多态的情况下看到它们。

场景#1

Event has_one :address # Event keeps child reference Address_id
Profile has_one :address # Profile keeps child reference Address_id
# Address doesn't keep any parent references in this example.

情景#2

Event has_one :phone # Event keeps child reference phone_id
Profile has_many :phones # Phones can keep parent profile_id as an optional field.
# Optional because it may belong to event.

场景#3

User has_many :contacts # Contacts keeps parent reference user_id
User has_many :issues # Issues keeps parent reference user_id
# There are no child references here

正如我所看到的,这些场景中的每一个都在等式中没有多态性。多态在这里很重要吗?有什么权衡取舍?

参考方向是否会影响子条目的删除?

1 个答案:

答案 0 :(得分:1)

当模型可以属于多个其他模型类型时,我使用多态。

您的方案的缺点:

1)这可能有效,因为它是一个has_one,但如果你想转移到has_many则不灵活。此外,当地址被破坏时,您将在事件或配置文件中留下悬空的address_id。坏消息。您必须手动管理,这是不必要的,容易出错。我在这里使用多态。

2)这对我来说简直是粗略的。为什么在Phone模型上混合belongs_to和has_one关联类型。那只是要求错误。我在这里使用多态。

3)因为这是一个有很多其他东西的用户,所以这里不需要多态性。这是一个非常直接的关系。不要在这里使用多态。

相关问题