如何添加记录在的has_many:通过关系

问题描述:

我有两个型号,GroupsEmployees它们通过has_many如何添加记录在的has_many:通过关系

class Group < ActiveRecord::Base 
    has_many :groupizations 
    has_many :employees, :through => :groupizations 
end 

class Employee < ActiveRecord::Base 
    has_many :groupizations 
    has_many :groups, :through => :groupizations 
end 

问题相关: 在view/employees/new.html.erb页面我希望能够让用户分配一个雇员到多个团队。为此,我会给他一个多选的下拉框,将填入所有组。 但我如何在我的create动作中捕获这些信息?

这是我到目前为止有:

在查看:

<% form_for @employee do |f| %> 
    <p> 
    <%= f.label :first_name %><br /> 
    <%= f.text_field :first_name %> 
    </p> 
    <p> 
    <%= f.label "Group" %><br /> 
    <%=select_tag 'groups[]', options_for_select(@groups.map {|s| [s.name, s.id]}), :multiple => true, :size =>8%> 
    </p> 
<p><%= f.submit %></p> 

创建行动:

def create 
    @employee = Employee.new(params[:employee]) 
    if @employee.save 
     flash[:notice] = "Successfully created employee." 
     redirect_to @employee 
    else 
     render :action => 'new' 
    end 
    end 

如何添加所有的用户选择的组groupizations


真,:大小=> 8%>

<p> 
    <%= f.label "Group" %><br /> 
    <%=select_tag 'employee[group_ids][]', options_for_select(@groups.map {|s| [s.name, s.id]}), :multiple => true, :size =>8%> 
</p> 

在创建方法则需要:

@employee = Employee.new(params[:employee]) 
@groups = Group.find(params[:employee][:group_ids]) 
@employee.groups << @groups 

并鉴于:

<%= select_tag 'employee[group_ids][]', options_for_select(@groups.map {|s| [s.name, s.id]}), :multiple => true, :size =>8%> 
+0

这是一个古老的答案,但这不会将雇员添加到所有t他选择的组合,也不会影响内部联接。这些如何完成? – Eric 2012-11-07 23:56:46