As you may (or may not) know, there are two ways to build a many-to-many (or N-N) relationship with Rails.
- 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 )
- 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
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
Categories:
Ruby on Rails |
Add a comment
»
