【问题标题】:Rails4 - How to drop an option from select based on the value?Rails4 - 如何根据值从选择中删除选项?
【发布时间】:2014-11-24 16:04:44
【问题描述】:

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

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

我想删除 value="1" 的选项“Native”。我的意思是我不希望它显示在某个地方。

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

请帮忙

【问题讨论】:

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


    【解决方案1】:

    使用 where not 并排除 id 为 1 的级别

    <%= 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' %>
    

    【讨论】:

    • 像魅力一样工作。感谢您分享将其移至助手的最佳实践方式
    【解决方案2】:

    这样的事情应该可以工作:

    <%= 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?

    【讨论】:

    • @Vimsha 的回答比我的好;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 2017-01-11
    • 2013-07-13
    • 1970-01-01
    相关资源
    最近更新 更多