显示多选导轨中的选定值

时间:2015-12-04 06:40:58

标签: ruby-on-rails select

多选:selected=>@campaign.categories.pluck(:name)无效,甚至没有出错

<%= f.select(:category, options_for_select(Category.all.map{|u| [u.name, u.id]}, :selected => @campaign.categories.pluck(:name) ), {}, {:multiple => true,:required => true, :class => 'form-control' }) %> 

2 个答案:

答案 0 :(得分:2)

您的代码存在一些问题。

Category.all.map{|u| [u.name, u.id]}

是实现所需内容的极其低效的方法,因为在处理之前将整个Category表加载到内存中。在这里,你真的需要使用pluck:

Category.pluck(:name, :id)

接下来,您不能将集合作为选定值。

您必须实际选择

<%= f.select(
  :category,
  options_for_select(
    Category.pluck(:name, :id),
    selected: @campaign.categories.pluck(:name).first # concrete value here, not a collection
  ),
  {},
  multiple: true,
  {:multiple => true,:required => true, :class => 'form-control'}
) %> 

答案 1 :(得分:1)

您可以尝试以下

<%= f.select(:category, options_for_select(Category.all.map{|u| [u.name, u.id]}, @campaign.categories.map{|j| [j.id]} ),:multiple => true, :required => true, :class => 'form-control' ) %>

<%= f.select(:category, options_for_select(Category.pluck(:name, :id), @campaign.categories.pluck(:id) ), :multiple => true, :required => true, :class => 'form-control' )