HABTM vs. using has_many :through

All,

I’ve heard recently about has_many :through as a necessary alternative
to HABTM (when the join table has it’s own id column, say, in a legacy
schema). However, is the prevailing Rails wisdom now that one should
use has_many :through in all cases?

If so, why?

Thanks,
Wes

Uber associationatire Josh S. has written a much recommended article
outlining the features and pros/cons of habtm and hmt:
http://blog.hasmanythrough.com/articles/2006/04/20/many-to-many-dance-off.

However, is the prevailing Rails wisdom now that one should
use has_many :through in all cases?
As with a lot of Rails wisdom the short answer is ‘it depends’ :0)

Steve

It may be heresy to some, but I still prefer HABTM over
has_many :through if the relationship I’m dealing with is simple.
i.e., if there’s no reason to store any metainfo in a join model, I
just use HABTM. I like my proxy collections!

This doesn’t mean I don’t love (and use) has_many :through for
situations when there does need to be metainfo stored about the
relationship. But I always ask myself first before I decide which to
use.

-Seth

Agreed.

Wes G. wrote:

All,

I’ve heard recently about has_many :through as a necessary alternative
to HABTM (when the join table has it’s own id column, say, in a legacy
schema). However, is the prevailing Rails wisdom now that one should
use has_many :through in all cases?

Not at all.

Think about the model first. Do you want to model your associations
explicitly, using a model class? In other words, are there things that
you want to say about the associations? (Can you put a name to them?
This may help you to find things that you might want to say about them.)
If so, use a model for the association… and then you will need the
:through capability to let you navigate through the association in a
single query.

If you just want the association to exist, with nothing further being
said about it, stick with HABTM.

In other words, I agree with others in this thread, but would like to
put the emphasis on thinking carefully about the domain model.

regards

Justin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs