I have groups and events.
To each event I want to invite some groups.
Groups has many inviting_events (events that invited a group) and each
event has_many groups invited.
I want to access through @group.inviting_events, @group.future_events
(the same but with a condition) and @event.invited_groups.
Is it better to create a new model that has_one group and has_one event
or to use a has_and_belongs_to_many relation?
I would say what you want is a new model that belongs_to group and
event -- namely, an invitation:
status (accepted, withdrawn, etc.)
You can then do:
class Event < AR::Base
has_many :groups, :through => "invitations"
and so forth, using conditions to fine-tune the various collections.
In general, when is better to use each one?
I have a feeling the answer you'll hear most is: habtm is
quasi-obsolete The main thing is that having a third model means
that you can express things more richly. In my example, Invitation
has a status and a created_at timestamp; those are just to illustrate
the fact that Invitation is a model in its own right, and can have its
own characteristics. A habtm link table is just a place to stash
foreign keys; it can't store any further information about the
The main thing that has stopped me from thinking of the :through
technique as a superset of habtm is the fact that with habtm you can
e = Event.find(m)
g = Group.find(n)
e.groups << g
However, there is now work being done on implementing << for the
:through technique. See
If is a recurring question, can you point me to a good paper?
and generally a lot of the stuff on that blog, which is Josh Susser's.