Subscribe
Contact



AddThis Social Bookmark Button
has_and_belongs_to_many or has_many :through?
As you may (or may not) know, there are two ways to build a many-to-many (or N-N) relationship with Rails.
  1. The first way uses has_and_belongs_to_many in both models. You'll have to create a join table that has no corresponding model or primary key. ( ActiveRecord will look by default for a join table called groups_users )
  2. class Group < ActiveRecord::Base has_and_belongs_to_many :users # foreign keys in the join table end class User < ActiveRecord::Base has_and_belongs_to_many :groups # foreign keys in the join table end The join table can have more attributes which can be filled with the push_with_attributes method: class User < ActiveRecord::Base has_and_belongs_to_many :groups # foreign keys in the join table def join_group(group) groups.push_with_attributes(group, :joined_at => Time.now) end end
  3. The second way uses a has_many association with the :through option and a join model: class Subscriptions < ActiveRecord::Base belongs_to :group # foreign key - programmer_id belongs_to :user # foreign key - project_id end class Group < ActiveRecord::Base has_many :subscriptions has_many :users, :through => :subscriptions end class User < ActiveRecord::Base has_many :subscriptions has_many :groups, :through => :subscriptions end
If you have to work with the relationship model as its own entity, thent you'll need to use has_many :through. Otherwise, you can just stick to has_and_belongs_to_many.

Add a comment :





© 2007 Eric Abouaf