Reputation: 14434
I'm trying to create a simple many-to-many association for my Artist
model. I've tried following the example here but for some reason its just not translating for my particular project. I basically just want users to belong to groups and reflect their memberships in my show view.
<!-- Shows the list of groups an artist belongs to -->
<% if @artist.groups.any? %>
<%= @artist.groups.each do |group| %>
<%= group.name %>
<% end %>
<% end %>
<!-- Shows the members of the groups -->
<% if @artist.members.any? %>
<p>
<b>Members:</b>
<% @artist.members.each do |member| %>
<%= member.name %>
<% end %>
</p>
<% end %>
I currently have my User model setup with a has_one association and works great. Now I just need to make it into a many_to many association to be able to call @artist.groups
. vs. @artist.group
. Would a a join table now be necessary to get this to work?
class Artist < ActiveRecord::Base
attr_accessor :group_id
has_many :members, class_name: 'Artist', foreign_key: 'group_id'
belongs_to :group, class_name: 'Artist', foreign_key: 'group_id'
end
Upvotes: 0
Views: 590
Reputation: 6096
You definitely need a join table for a many-to-many association.
Try something like this (this is from memory so may need some adjusting):
class Membership
# attributes "artist_id" and "group_id"
belongs_to :member, class_name: "Artist"
belongs_to :group, class_name: "Artist"
end
class Artist
# no foreign keys required
has_many :group_memberships, class_name: "Membership", foreign_key: :group_id
has_many :members, through: :group_memberships
has_many :memberships, foreign_key: :member_id
has_many :groups, through: :memberships
end
Then your view can stay the same as it is in the question.
You probably also want to add a unique index to your memberships
table:
add_index :memberships, :member_id
add_index :memberships, :group_id
add_index :memberships, [:member_id, :group_id], unique: true
... with the appropriate validates_uniqueness_of
validation in your Artist
model.
Upvotes: 1