ActiveRecord Associations: Any gotchas if has_many WITHOUT corresponding belongs_to?

爱⌒轻易说出口 提交于 2019-12-07 06:35:18

问题


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?


回答1:


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.




回答2:


The model with the belongs_to associations holds the foreign keys (e.g. messages table would have phone_id and email_id columns).

The belongs_to association combined with has_many lets you easily access associated records:

phone.messages
message.phone

So without the belongs_to and FK columns, the has_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.



来源:https://stackoverflow.com/questions/4925827/activerecord-associations-any-gotchas-if-has-many-without-corresponding-belongs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!