Well, you've got two models, Contact and Group. These two guys are clearly going to have their own tables (probably 'contacts' and 'groups' if you're following the Rails conventions). Since a contact can be in many groups, and a group can have many contacts, you've got what's called a many-to-many relationship between these models. There are basically two ways to implement this in Rails: has_and_belongs_to_many
or has_many :through
. Which one is best for you will depend a little on your situation.
has_and_belongs_to_many
is probably the path of least resistance. You put a couple lines in your models like so:
# contact.rb
has_and_belongs_to_many :groups
# group.rb
has_and_belongs_to_many :contacts
...and create a table called 'contacts_groups' with the columns contact_id
and group_id
, and you're basically good to go. Easy peasy.
On the other hand, there are some advantages to using an association model with has_many :through
. In this approach, you create another model, say, GroupMembership, and set up your models like so:
# contact.rb
has_many :group_memberships # this isn't strictly required, but I'd recommend it
has_many :groups, :through => :group_memberships
# group_membership.rb
has_many :groups
has_many :contacts
# group.rb
has_many :group_memberships # again, recommended but not required
has_many :contacts, :through => :group_memberships
This gives you most of the same convenience methods as has_and_belongs_to_many
, and also lets you store any extra data you might want about the association, like the date they joined the group or the reason they were added. Even if you don't have any of that now, it's nice to account for the possibility of adding it later. Also, this lets you take a more RESTful approach to adding and removing contacts to and from groups, if that's something you're interested in, since you can model it in terms of creating and destroying GroupMembership resources.
By and large, I tend to lean toward the latter approach, especially as I've gotten more in to RESTful architectures. On the other hand, if you're not worried about REST and you're certain you'll never want to keep any extra information about memberships, has_and_belongs_to_many
is probably simpler and requires less code to get working. For more in-depth information on the differences and implementation details, see the ActiveRecord Associations API docs.