Hi --
Hello, 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:
Event Group Invitation event_id group_id status (accepted, withdrawn, etc.) created_at
You can then do:
class Event < AR::Base has_many :invitations 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 association.
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 do this:
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 http://blog.hasmanythrough.com/articles/2006/08/19/magic-join-model-creation
If is a recurring question, can you point me to a good paper?
http://blog.hasmanythrough.com/articles/2006/04/20/many-to-many-dance-off and generally a lot of the stuff on that blog, which is Josh Susser's.
David