[英]Creating a simple many-to-many self-join association in Rails
I'm trying to create a simple many-to-many association for my Artist
model. 我正在尝试为我的
Artist
模型创建一个简单的多对多关联。 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. 我目前使用has_one关联来设置用户模型,并且效果很好。 Now I just need to make it into a many_to many association to be able to call
@artist.groups
. 现在,我只需要使其成为多对多关联即可调用
@artist.groups
。 vs. @artist.group
. 与
@artist.group
。 Would aa 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
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: 您可能还想向
memberships
表添加唯一索引:
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. ...在您的
Artist
模型中使用适当的validates_uniqueness_of
验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.