2010-08-12 75 views
1

我有兩個型號,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

回答

2


真,:大小=> 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> 
0

在創建方法則需要:

@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

相關問題