开发者

how to add records in a has_many :through relationship

I have two models, Groups and Employees which are related by a 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

Question: In page view/employees/new.html.erb I want to be able to let the user assign an employee to multiple groups. For this I will give him a multiple select drop down box that will be populated with all the groups. but How do I capture this information in my create action??

this is what I have so far:

in View:

<% form_for @employee do |f| %>
  <p开发者_如何学C>
    <%= 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>

in Create action:

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

How Do I add all the groups that user selected to the groupizations



true, :size =>8%>

to

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


In create method you will need:

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

and in view:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜