Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_and_belongs_to_many vs has_many through

Please explain the difference between has_and_belongs_to_many and has_many through relationship. When and where to use which one?

like image 997
Mohit Jain Avatar asked May 06 '10 11:05

Mohit Jain


People also ask

What is difference between Has_and_belongs_to_many and Has_many through?

Aside from the actual code you write, the main difference between the two approaches is that in a has_many :through relationship, the JOIN table has its own model, while a has_and_belongs_to_many relationship has no JOIN model, just a database table.

Has and belong to many VS has many through?

Stories can belong to many categories. Categories can have many stories. has_many :through gives you a third model which can be used to store various other pieces of information which don't belong to either of the original models. Person can subscribe to many magazines.


2 Answers

As far as I can remember, has_and_belongs_to_many gives you a simple lookup table which references your two models.

For example,

Stories can belong to many categories. Categories can have many stories.

Categories_Stories Table story_id | category_id 

has_many :through gives you a third model which can be used to store various other pieces of information which don't belong to either of the original models.

For example

Person can subscribe to many magazines. Magazines can have many subscribers.

Thus, we can have a subscription model in the middle, which gives us a similar table to the earlier example, but with additional properties.

Subscriptions Table person_id | magazine_id | subscription_type | subscription_length | subscription_date  

And so on.

like image 68
Dan Avatar answered Sep 20 '22 19:09

Dan


From http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don’t need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you’ll need to remember to create the joining table in the database). You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.

like image 39
Tadas T Avatar answered Sep 18 '22 19:09

Tadas T