Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a multi select list in rails

I'm trying to make a multi select list box in Rails. My view code is:

<div>
  <%=nested_form_for(@allocation) do|builder|%>
    <%=builder.label :song_id, "Pick a song" %>

    <%=builder.select :song_id, options_for_select(
    Song.all.collect {|s| [ [s.title, s.artist].join(" by "), s.id ] }, 
    { include_blank: true, multiple: true, size: 5 }) %>

    <%=builder.submit "Add Song", class: "btn btn-large btn-primary" %>
  <% end %>
</div>

At the moment I just have the normal single selectbox but I want to convert this to a multiselect. Any pointers would be much appreciated. Thanks in advance

like image 503
TangoKilo Avatar asked Jan 16 '23 03:01

TangoKilo


2 Answers

This seems to have worked in my case:

<%= builder.select(
    :song_id,
    options_for_select(@selections),
    {},
    {multiple: true, size: 10})
%>
like image 76
TangoKilo Avatar answered Jan 25 '23 23:01

TangoKilo


Often you need to use a select_tag however there are lots of different ways this can work depending on where you are getting the data from

<%= select_tag '@Mymodel[myattribute][]',
    options_from_collection_for_select(SelectionModel, "id", "title", @Mymodel.myattribute),
    :multiple => true, :size =>10 }
%>

perhaps yours would look something like

<%= select_tag '@allocation[song_id][]',
    options_from_collection_for_select(Song.all., "id", "title", @allocation.song_id),
    { :multiple => true, :size =>10 }
%>

an example of this can be seen, here...

http://www.gilluminate.com/2007/02/15/best-way-to-do-multiple-select-combo-boxes-in-rails/

like image 25
Purple Hexagon Avatar answered Jan 25 '23 23:01

Purple Hexagon