我有两个模型Groups
和Employees
,它们与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
答案 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%>