如何有许多一对多的关系轨 [英] How to have many-to-many relationship in rails
问题描述
我是新来的铁轨,并正尝试建立在我的Rails项目一多对一对多的关系。我有一个小的策略,但我不知道它的正确方法。
I am new to rails, and am trying to set up a many-to-many relationship in my rails project. I have a small strategy, but I am not sure if its the correct way.
目的:
我有用户的一个表,和组的表。用户可以是多种基团的一部分,并且每个基团可以有许多用户。
Aim: I have a table of users, and a table of groups. Users can be part of many groups, and each group may have many users.
策略:
- 设置了用户迁移到有名称:字符串
- 设置了集团迁移到有名称:字符串
- 设置了一个连接表迁移
- 设置了用户模式,这样它会has_and_belongs_to_many:组
- 设置了组模式,这样它会has_and_belongs_to_many:用户
这会是正确的策略是什么?谢谢!
Would this be the correct strategy? Thanks!
这答案的 Railcast摘要:
对于那些有兴趣 - Railcast建议您使用的has_many:通过协会自上述策略有,你不能添加额外的特定的关系,信息的限制。
Railcast Summary from answer: For those that are interested - Railcast suggests you to use a has_many :through association since the strategy above has the limitation that you cannot add extra relation-specific information.
检查: http://kconrails.com/tag/has_many/
推荐答案
首先,我认为,你有一个用户模型与现场名和一组模型具有name字段。
First, I assume, you have a user-model with a field "name" and a group-model with a field "name".
您需要的用户和组之间的模式。让我们把它叫做分组:
You need a model between users and groups. Let's call it grouping:
rails g model grouping user_name:string group_name:string
在分组模型(grouping.rb),你把:
In the grouping-model (grouping.rb), you put:
belongs_to :user
belongs_to :group
在用户模式:
has_many :groupings, :dependent => :destroy
has_many :groups, :through => :groupings
而在组模型:
has_many :groupings, :dependent => :destroy
has_many :users, :through => :groupings
在_form文件进行编辑或更新用户的个人资料,你把:
In the _form file to edit or update a user's profile, you put:
<div class="field">
<%= f.label :group_names, "Groups" %>
<%= f.text_field :group_names %>
</div>
最后,用户级必须知道,如何处理从表单的信息做。 INSERT INTO user.rb:
And, finally, the User-class must know, what to do with the information from the form. Insert into user.rb:
attr_writer :group_names
after_save :assign_groups
def group_names
@group_names || groups.map(&:name).join(' ')
end
private
def assign_groups
if @group_names
self.groups = @group_names.split(/\,/).map do |name|
if name[0..0]==" "
name=name.strip
end
name=name.downcase
Group.find_or_create_by_name(name)
end
end
end
assign_groups删除空白和downcases所有的话,所以你不会有多余的标签。
assign_groups removes whitespace and downcases all words, so you won't have redundant tags.
现在,您可以显示群组在他或她的个人资料的演出文件用户:
Now, you can show the groups for a user in the show file of his or her profile:
<p>Groups:
<% @user.groups.each do |group|%>
<%= group.name %>
<% end %>
</p>
希望,帮助。
这篇关于如何有许多一对多的关系轨的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!