Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord Associations: Any gotchas if has_many WITHOUT corresponding belongs_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?

like image 519
jpw Avatar asked Feb 07 '11 19:02

jpw


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is a polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

What is has_ many?

You use a has_many :through relationship when you want to interact with the join table as a Rails model, complete with primary keys and the ability to add custom columns to the joined data.


2 Answers

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.

like image 121
gertas Avatar answered Sep 24 '22 13:09

gertas


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.

like image 33
Dennis Avatar answered Sep 24 '22 13:09

Dennis