Rails select with multiple options only sends one

2019-05-27 10:23发布

问题:

I have this form :

<form accept-charset="UTF-8" action="/contracts/<%= params[:id] %>/addConsultants" method="POST" id="updateConsultants"><!---->

  <div style="margin:0;padding:0;display:inline">
    <input name="utf8" type="hidden" value="✓">
    <input name="authenticity_token" type="hidden" value="<%= session[:_csrf_token] %>">
  </div>

  <div class="consultant_selector">
    <h2>Consultants</h2>

    <select name="consultants_available" size="10" multiple>
      <% @users.each do |u| %>
        <option value="<%= u[:id_user] %>"><%= u[:name] %></option>
      <% end %>
    </select>

    <ul>
      <li class="triangle_right" id="add_consultant"></li>
      <li class="triangle_left" id="remove_consultant"></li>
    </ul>

    <select name="consultants_selected" size="10" multiple>
    </select>
  </div>

  <div>
    <input type="submit" value="Mettre à jour" />
  </div>
</form>

And in my controller :

  def add_consultants
    @contract = Contract.find(params[:id])
    @consultants = params[:consultants_selected];
    puts "------ Consultants: #{@consultants}"

    redirect_to contract_path
  end

The idea is that I can select names from the first select, move them to the second by clicking on the triangle and then submit the form to assign these names to a contract. However, when I do this the call to puts only prints one ID out of the 3 I have in the second select (all three of them have the selected attribute to true). How do I get multiple values?

回答1:

Just found the answer here : https://stackoverflow.com/a/2196522/1796742

Changing the name of the second select from:

<select name="consultants_selected" size="10" multiple>
</select>

To :

<select name="consultants_selected[]" size="10" multiple>
</select>

Worked.