4

我正在尝试在 Rails 中创建一个多选列表框。我的视图代码是:

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

目前我只有普通的单选框,但我想将其转换为多选。任何指针将不胜感激。提前致谢

4

3 回答 3

6

这在我的情况下似乎有效:

<%= builder.select(
    :song_id,
    options_for_select(@selections),
    {},
    {multiple: true, size: 10})
%>
于 2012-07-12T11:33:59.793 回答
4

通常您需要使用 select_tag ,但是根据您从哪里获取数据,有很多不同的方式可以工作

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

也许你的看起来像

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

可以看到一个例子,这里......

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

于 2012-07-12T11:32:04.663 回答
-1

如果你想通过 jquery 来做,下面的链接会帮助你

http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/

于 2012-07-12T11:21:17.190 回答