Habtm vs. has_many/belongs_to


#1

In AWDWR David says (pg 232),

"When a Join Wants to Be a Model:
While a many-to-many relation with attributes can often seem like the
obvious choice, itâ??s often a mirage for a missing domain model. When
it is, it can be advantageous to convert this relationship into a
real model
and decorate it with a richer set of behavior. This lets you
accompany the
data with methods.
As an example, we could turn the articles_users relationship into a new
model called Reading. This Reading model will belong_to both an article
and a user. And itâ??s now the obvious spot to place methods such as
find_popular_articles( ), which can perform a group by quer y and
return the
articles that have been read the most. This lightens the burden on
the Arti-
cle model and turns the concept of popularity into a separated concern
that naturally sits with the Reading model. "

First, I assume this means that the other model definitions need to
have a “has_many:” declaration for this new model that will belong to
each?

Is anyone aware of where I might look to find more information on
this kind of alternative setup? How often have any of you chosen the
method described here as opposed to just using HABTM? What are some
of the main trade-offs in using either?

Thanks in advance!

Michael J.
removed_email_address@domain.invalid


#2

Michael,

Generally the switch from HABTM to a Model Join is when the link will
actually store extra data besides the link information. The example
above references adding popularity to the link, which prompted the
writer to switch. There is a way to push that extra data into the join
while using HABTM but it can get ugly fast and usually the user will
want to add data from an interface which lends itself to having a
Model Join.

The practice that the example is promoting is to create the Model Join
whenever you have extra data in the joining table.

Carl


#3

Michael J. wrote:

First, I assume this means that the other model definitions need to
have a “has_many:” declaration for this new model that will belong to
each?

Is anyone aware of where I might look to find more information on
this kind of alternative setup? How often have any of you chosen the
method described here as opposed to just using HABTM? What are some
of the main trade-offs in using either?

I blogged about has_many :through associations to kick off my blog last
month. I think my article answers many of your questions.

http://blog.hasmanythrough.com/articles/2006/02/28/association-goodness

Since then 1.1 got a new kind of has_many :through where the middle
table looks like

class Middle < AR
belongs_to :left
has_many :rights
end

instead of

class Middle < AR
belongs_to :left
belongs_to :right
end

I’ll try and write something about that soon, cause it’s nifty.

–josh
http://blog.hasmanythrough.com