views:

211

answers:

4

I have been hearing a lot of buzz around has_many :through(HMT) vs has_and_belongs_to_many (HABTM). This post covers most of its benefits. Okay, HMT sure has some real good benefits over HABTM. However, what I wanted to know that when should I know that I should be using HMT over HABTM? Often I am in a situation where I believe that plain vanilla HABTM association would solve my problem (plus lighter data and design) without having to use swanky benefits of HMT. But the buzz about HMT makes me want to doubt if I took the right decision of choosing HABTM. How could I be sure that I made the right decision?

+3  A: 

If you're 100% sure you're never going to need to add another field to the associative table, then HABTM is fine. If don't need a third field right now but think that there's a possibility that someday you might, then you should go with HMT as you'll have more flexibility.

Andy Gaskell
A: 

I think you could probably get away with starting HABTM and then changing to has_many :through down the line--it would just require a migration renaming the join table and adding any fields you want. Then, you just create the associative model corresponding with the table, and it should work.

Kyle Slattery
+3  A: 

Does it work? Then you made the right decision.

It may not be the best decision in the long run if haven't completely mapped out your database relations. However this is not a decision that will haunt you for the entire development period of the project. If you followed directions in setting up your HABTM relationship, then migrating to a HMT relationship is fairly trivial.

Here's what needs to be done.

  • Add primary key called id to the join table that auto increments, and fill in ids for items already in the table.
  • Create a join model for the join table that belongs_to both sides of the relationship
  • Replace the habtm declarations with has_many :join_models, and has_many :others, :through => :join_models

Personally I prefer the HMT but most of my join models need to keep track of more than just the association.

P.S. That blog post is out of date. HMT now supports proxy collections.

EmFi
A: 

Just extra 5 minutes of work spent in the beginning creating the HTM relationship can save you a lot of trouble later. Migrating from HABTM to HTM may not be very simple once you gathered a lot of data.

I would definitely suggest going with HTM and skipping HABTM. No situation that I know of may compel you to use HABTM. Most situations however, will compel you to use HTM (adding more data to relationship for eg.)

Swanand