Ruby Active Record Associations in Rails Active Record Associations Has Many Through Associations

Eylon Cohen
Eylon Cohen
4,779 Points

belongs_to_and_has_many vs has_many_through

In what cases should I use belongs_to_and_has many? I usually don't know if I will ever need to use this joint table. for space? for convience?

1 Answer

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

Here's a summary of the differences:

https://stackoverflow.com/questions/2780798/has-and-belongs-to-many-vs-has-many-through

One common bit of advice is to always use has_many :through unless you are certain you will never need to add fields to the join table, because it's a bit of a pain to convert from has_and_belongs_to_many to has_many :through. But HABTM is supposedly a bit more efficient, so there are those who say you should use HABTM until you know you need has_many :through. In the end, the choice is yours.