becos life is about pushing the envelope playfully



Rails has_and_belongs_to_many VS has_many :through

It’s really easy to setup a many-to-many relationships in Rails. There are 2 ways of doing this:

1) has_and_belongs_to_many association

2) has_many :through

I’m not going to touch on the details of each because there’s great documentation provided in the above links. However, I do want to point out the flaws and limitations of has_and_belongs_to_many association.

Like in this example,

Photo Credit: http://guides.rubyonrails.org

the way to connect the assemblies and parts models is to create a table (named after both models, assemblies_parts) with 2 columns, assembly_id and part_id. It’s a table not a model. It’s definitely much easier to create a has_and_belongs_to_many association than has_many :through but  has_and_belongs_to_many association doesn’t work in most real life situations.

1) Notice there’s no id column in the assemblies_parts model? Because of this, there’s no way to add additional attribute to this table. Let’s say you want to know which assembly/part combination is the most popular. In a has_and_belongs_to_many association, you can’t add an additional attribute, e.g. popular_count to the table.

2) As there’s no model created, there’s no way to add validations or callbacks in a has_and_belongs_to_many setup.

I learned it the hard way and had to convert my code from has_and_belongs_to_many to has_many :through. As your app gets more complicated with rules and processes, make sure your associations is setup in a way that’s flexible enough to incorporate the changes easily. Moving forward,  my choice is to always use has_many :through because I don’t want to create road blocks for myself down the road.

6:06 pm, by aihui
permalink
tagged: tech, rails,


   Comments