ActiveRecord关联:如果has_many WITHOUT相对应的belongs_to有任何麻烦吗? [英] ActiveRecord Associations: Any gotchas if has_many WITHOUT corresponding belongs_to?
问题描述
电话中有很多消息。
电子邮件地址中有很多消息。
An email address has many messages.
消息要么属于到电话,电子邮件或两者都不到。 belongs_to
关联是可选的。
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:
- 电话型号
has_many:messages
- 电子邮件型号
has_many:messages
- 消息模型没有
belongs_to:phones :: email
- Phone model
has_many :messages
- Email model
has_many :messages
- Message model does NOT have
belongs_to :phones, :email
这还好吗,或者有某种适当的方法来指定 can_belong_to关系吗?
Is this okay or is there some proper way to specify a "can_belong_to" relationship?
推荐答案
这是完全正确的单向关系。某些纯粹主义者有时同时使用这两种方法,并且在使用 validates_associated 。
It is completely correct unidirectional relation. Using both is sometimes called "curcular dependency" by some purists and may cause problems when using validates_associated.
从另一端仅使用 has_many:messages
要从一封邮件中检索电话信息还不够。通常,这是为了方便。
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.
这篇关于ActiveRecord关联:如果has_many WITHOUT相对应的belongs_to有任何麻烦吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!