我正在尝试为我的Artist
模型创建一个简单的多对多关联。我试过跟随示例here,但由于某种原因它只是没有翻译我的特定项目。我基本上只希望用户属于群组,并在我的节目视图中反映他们的会员资格。
<!-- 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 %>
我目前的用户模型设置为has_one关联,效果很好。现在我只需要将其转换为多个关联即可调用@artist.groups
。与@artist.group
。现在是否需要联接表才能使其正常工作?
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
答案 0 :(得分:1)
您肯定需要一个用于多对多关联的连接表。
尝试这样的事情(这是从内存中所以可能需要调整一下):
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
然后您的观点可以与问题中的观点保持一致。
您可能还想在memberships
表中添加唯一索引:
add_index :memberships, :member_id
add_index :memberships, :group_id
add_index :memberships, [:member_id, :group_id], unique: true
...在validates_uniqueness_of
模型中进行适当的Artist
验证。