Godzilla74 Godzilla74 - 1 month ago 8
Ruby Question

Rails multiple select form

I'm trying to make a multiple select form where a user can move IP addresses from the left select box to the right side (I'm not sure what that object is called).

I have my basic form code, but it's showing a dropdown instead (I've taken out the irrelevant code):

<%= form_for @network_host_groups do |f| %>
<%= f.select :network_hosts, @network_hosts.collect { |n| [ n.ip_address, n.id ] } multiple: true, include_blank: false %>
<%= f.submit "Add", class: "btn btn-success" %>
<% end %>


Which looks like:

enter image description here

However, I'm trying to get something like:

enter image description here

What's the best way to go about doing this?

Answer

If you take a look at the docs for select you'll see it takes 2 sets of options: options - for Rails options, and html_options for additional attributes to include on the generated HTML <select> tag.

include_blank is a Rails option, whereas multiple is an HTML attribute so these need to be passed in separate hashes:

Also, it looks like when tidying your code to post the question you've lost a comma after the end of your collect block so be sure to make sure that's included when retrying this.

That's the reason why available hosts is appearing as a single item dropdown instead of a list anyway. Implementing the moving between "available" and "assigned" lists is beyond the scope of a single question.