Has and Belongs to Many Example Repo
Railscast 047 Two Many-to-Many prompted me to ask this. He showed an has_many_and_belongs_to
and an has_many :through
example. From what the episode, Ryan Bates seems to generally like has_many :through
better because it adds flexibility. What are some of the reasons behind this conclusion?
Differences
The Rails Guides on Associations has a section about this.
For has_and_belongs_to_many
the relationship is built through a join table using only two models. A has_many :through
relationship creates a third model that belongs_to
the two models in the relationship. The circumstances you would want a has_many :through
association would be:
if you need validations, callbacks, or extra attributes on the join model.
A case where you might want to have a has_many :through
associations would be if you have a feature of ‘following’ within the app. Each user has followers and following users. One relationship could be established, but both do not necessarily have to be established. In the case of followers and following users, you would actually need two relationship tables in the database. ActiveRecord provides the ability to ‘reverse’ a relationship based on what the foreign key is.
There could be a relationships table with follower_id
and followed_id
. To find a user’s followed users, then you would set the foreign key to the follower_id
. To find a user’s followers, then you would set the foreign key to the followed_id
and rename this relationship to something like reverse_relationship
within the model.