【问题标题】:Rails - disable option in select (based on the condition)Rails - 在选择中禁用选项(基于条件)
【发布时间】:2012-07-06 14:35:48
【问题描述】:

我有选择:

= f.select(:category_id, @categories, :html_options => {:class => 'select_box'}, {:disabled => true if category.id == 18})

上面这段代码明明是报错,但是如何根据id禁用一个选项呢?

【问题讨论】:

    标签: ruby-on-rails select helper


    【解决方案1】:

    还没有测试过,但是在你的控制器中你不能这样做

    @checkvar = @category.id == 18 ? true : false
    

    然后在视图中

    f.select(:category_id, @categories, :html_options => {:class => 'select_box'}, {:disabled => @checkvar})
    

    或者在模型中写一个函数来测试

    def disable_select 
        if self.id == 18
            true
        else 
           false
        end
    end
    

    然后在视图中

    f.select(:category_id, @categories, :html_options => {:class => 'select_box'}, {:disabled => @category.disable_select})
    

    【讨论】:

    • 这不适用于 HTML5。因为它只会添加没有值的 disabled 属性,并且在 HTML5 中仍然有效。所以,你需要一个帮助方法,它返回一个空哈希或带有禁用选项集的哈希
    【解决方案2】:
    <%= f.select :status, STATUSES.map{|s| [s.titleize, s]}, { disabled: DISABLED_STATUSES.map{|s| [s.titleize, s]} %>
    

    【讨论】:

      【解决方案3】:

      最近遇到这个问题并使用了以下解决方案:

      #view
      = f.select(:category_id, @filtered_categories, :html_options => {:class => 'select_box'}
      
      #controller
      @filtered_categories = Category.all.select do |category|
        [logic here]
      end
      

      【讨论】:

        【解决方案4】:

        对于select_tag,我们可以这样做:

        <%= select_tag "sample", options_for_select(
            [['A', 'a'], ['B', 'b'], ['C', 'c']]),
            {class: 'form-control', disabled: data.present? == false ? true : false}
        %>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-20
          • 2018-12-12
          • 1970-01-01
          • 2011-11-19
          • 2012-11-29
          • 1970-01-01
          相关资源
          最近更新 更多