Rails4 - 如何根据值从select中删除选项?

时间:2014-11-24 16:04:45

标签: html ruby-on-rails ruby-on-rails-4

如何根据值从以下项目中删除项目?

<%= select_tag :langlevel, options_for_select(Level.order(:name).map {|item| [item.name, item.id]}), id: 'langlevel_id', :class => 'form-control lang' %>

它给了我这个

<select class="form-control lang" id="langlevel_id" name="langlevel"><option value="2">A1:Beginner</option>
<option value="3">A2:Elementary</option>
<option value="4">B1:Pre-Intermediate</option>
<option value="5">B2:Intermediate</option>
<option value="6">C1:Upper Intermediate</option>
<option value="7">C2:Advanced</option>
<option value="1">Native</option></select>

我想删除选项&#34; Native&#34;其值为&#34; 1&#34;。我的意思是我不希望它出现在一个地方。

<option value="1">Native</option></select>

请帮助

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

<%= select_tag :langlevel, options_for_select(Level.all.order(:name).reject { |s| s.id == 1 }.map {|item| [item.name, item.id]}), id: 'langlevel_id', :class => 'form-control lang' %>

你必须先拒绝然后再映射。

从这里开始:Exclude option from collection.map in Ruby on Rails?

答案 1 :(得分:1)

使用where not并排除ID为<1 / p>的级别

<%= select_tag :langlevel, options_for_select(Level.where.not(:id => 1).order(:name).map {|item| [item.name, item.id]}), id: 'langlevel_id', :class => 'form-control lang' %>

将这个逻辑转移到帮助者可能更干净

def non_native_levels_as_options
   Level.where.not(:id => 1).order(:name).map {|item| [item.name, item.id]}
end

<%= select_tag :langlevel, options_for_select(non_native_levels_as_options), id: 'langlevel_id', :class => 'form-control lang' %>