ActiveRecord 关联:如果 has_many 没有对应的 own_to,有什么问题吗?
一部手机有很多条信息。
一个电子邮件地址包含许多消息。
消息要么属于电话、电子邮件,要么两者都不属于。 belongs_to
关联是可选的。
以下关联似乎适用于这些关系:
- 电话模型
has_many :messages
- 电子邮件模型
has_many :messages
- 消息模型没有
belongs_to :phones, :email< /code>
这可以吗?或者是否有某种正确的方法来指定“can_belong_to”关系?
A phone has many messages.
An email address has many messages.
A message either belongs to a phone, email, or neither. The belongs_to
association is optional.
The following associations seem to work fine for these relationships:
- Phone model
has_many :messages
- Email model
has_many :messages
- Message model does NOT have
belongs_to :phones, :email
Is this okay or is there some proper way to specify a "can_belong_to" relationship?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是完全正确的单向关系。使用两者有时被一些纯粹主义者称为“循环依赖”,并且在使用 validates_linked。
当您想要从一条消息中检索电话信息时,从另一方仅使用
has_many :messages
可能还不够。一般来说都是为了方便。It is completely correct unidirectional relation. Using both is sometimes called "curcular dependency" by some purists and may cause problems when using validates_associated.
From the other side using only
has_many :messages
may be not enough when you want retrieve phone information from one message. Generally it is matter of convenience.具有
belongs_to
关联的模型保存外键(例如,messages
表将具有phone_id
和email_id
列)。belongs_to
关联与has_many
相结合,让您可以轻松访问关联记录:因此,如果没有
belongs_to
和 FK 列,has_many
> 关联不是很有用。在这种情况下,您可能需要多对多关系,例如
has_and_belongs_to_many
因为一条消息可以有多个收件人。The model with the
belongs_to
associations holds the foreign keys (e.g.messages
table would havephone_id
andemail_id
columns).The
belongs_to
association combined withhas_many
lets you easily access associated records:So without the
belongs_to
and FK columns, thehas_many
association isn't very useful.It seems like in this case you may want a many-to-many relationship such as
has_and_belongs_to_many
as a message can have many recipients.