如何在has_many:through关系中添加记录

时间:2010-08-12 11:00:55

标签: ruby-on-rails activerecord

我有两个模型GroupsEmployees,它们与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 个答案:

答案 0 :(得分:2)

      
       true,:size =&gt; 8%&gt;     

<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>

答案 1 :(得分:0)

在create方法中,您需要:

@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%>