如何默认选择form_for选择所有值

时间:2016-04-13 09:18:13

标签: ruby-on-rails forms

在带有form.select的表单中,我希望默认选择所有选项。我有年龄模型,显示所有年龄的形式,我希望默认选择所有选项。我的代码如下:

f.select(:age, options_for_select(Age.pluck(:age, :id) , :selected => @campaign.ages.pluck(:id)),{},{:multiple=>true , :required=>true}) 

2 个答案:

答案 0 :(得分:0)

试试这个:

f.select(:age, options_for_select(Age.pluck(:age, :id) , :selected => @campaign.ages.pluck(:id)),{:multiple=>true , :required=>true}) 

答案 1 :(得分:0)

我通过检查做到了这一点。如果用户被创建为新记录,那么我选择了所有这些记录,如果是编辑,我只会显示所选的。正如下面的代码所说的那样:

<% if @campaign.new_record? %>
  <%= f.select(:age, options_for_select(Age.pluck(:age, :id), :selected => Age.pluck(:id) ), {}, {:multiple => true,:required => true ,:class => 'form-control'}) %>
<% else %>    
  <%= f.select(:age, options_for_select(Age.pluck(:age, :id), :selected => @campaign.ages.pluck(:id) ), {}, {:multiple => true,:required => true ,:class => 'form-control'}) %>
<% end %>