Joe Morano Joe Morano - 3 months ago 16
Javascript Question

Rails: Selectize multiselect only submits the last selection

I have a form to create a new User. I'm trying to use

gem selectize-rails
to allow the option to add multiple related Users:

views/users/new.html.erb

<%= form_for @user, :url => users_path do |f| %>
<select name="users" id='select-user'>
<option value="">Select at least one user</option>
<% User.all.each do |user| %>
<option value="<%= user.name %>"><%= user.name %></option>
<% end %>
</select>
<script type="text/javascript">
var select = $('#select-user').selectize({
persist: false,
maxItems: 3,
create: false,
valueField: 'name',
labelField: 'name',
searchField: ['name'],
render: {
item: function(item, escape) {
return '<div>' +
(item.name ? '<span class="select-name">' + escape(item.name) + ',</span>' : '') +
'</div>';
},
option: function(item, escape) {
var label = item.name;
return '<div>' +
'<span class="select-label">' + escape(label) + '</span>' +
'</div>';
}
},
preload: false,
load: function(query, callback) {}
});
</script>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>


controllers/user_controller.rb

def new
@user = User.new
end

def create
@user = User.new(user_params)
if @user.save
redirect_to root_path
else
redirect_to new_user_path
end
end

private

def user_params
params.require(:user).permit(:name, :users)
end


On
new.html.erb
, the code works fine: I can add up to three Users. But when I submit it,
params["users"]
only contains the last User I added, no matter how many I tried to add. Does anyone know why this might be?

Answer

Change:

<select name="users" id='select-user'>

to

<select name="users" id='select-user' multiple='multiple'>

That should make rails expect to get multiple values from select.

The whole select section, can be rewritten using the rails select helper.

<select name="users" id='select-user'>
  <option value="">Select at least one user</option>
  <% User.all.each do |user| %>
    <option value="<%= user.name %>"><%= user.name %></option>
  <% end %>
</select>

becomes

<%= select :user, options_for_collection_for_select(User.all, :name, :name),
  { prompt: "Please select.." },
  { multiple: true } %>

See http://guides.rubyonrails.org/v2.3.11/form_helpers.html#making-select-boxes-with-ease and http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html for more details.

Comments