Many-to-many
There are two ways to build a many-to-many relationship. The first and preferred
way uses a has_many
association
with the :through
option
and a join model, so there are two stages of associations:
class UserRole < ActiveRecord::Base belongs_to :user belongs_to :role end class User < ActiveRecord::Base has_many :user_roles has_many :roles, :through => :user_roles end class Role < ActiveRecord::Base has_many :user_roles has_many :users, :through => :user_roles end
The second way uses has_and_belongs_to_many
in both models. This requires a join table that has no
corresponding model or primary key:
class User < ActiveRecord::Base has_and_belongs_to_many :roles end class Role < ActiveRecord::Base has_and_belongs_to_many :users end
See Figure 3.
Get Rails Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.