views:

20

answers:

2

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

A: 

Hi try change this part

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

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>
Bohdan Pohorilets
A: 

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