【问题标题】:Select_tag: Style and Modify Options Upon ConditionSelect_tag:根据条件设置样式和修改选项
【发布时间】:2016-01-19 05:45:04
【问题描述】:

我有一个form_categories 表,其中有一个名为active 的列,其类型为tinyint/boolean。如果表单类别记录的活动属性为真,则它是活动的。如果为 false,则它处于非活动状态。

我有一个显示form_categories 表中的所有记录的选择框。我想将 inactive form_category 选项设置为红色,以便向用户传达该 form_category 处于非活动状态。或者更好的是,我想在每个不活动的 form_category 选项旁边加上括号:(inactive) 用红色字母表示。

这可能吗?

下面是我的选择框:

<%= form_tag some_path, method: :get do %>
  <%= label_tag "Choose Category" %><br>
  <%= select_tag :category_id, options_from_collection_for_select(FormCategory.all, :id, :name), include_blank: true %>
<% end %>

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您可以使用options_for_select 并自己提供选项哈希:

    options_for_select(form_categories_options, 1) # Where 1 is the current selected option; you would use some value passed from the controller for it
    

    对于form_categories_options,您可以使用帮助器,例如:

    def form_categories_options
      FormCategory.all.map do |form_category|
        if form_category.inactive
          ["#{form_category.name} (inactive)", form_category.id]
        else
          [form_category.name, form_category.id]
        end
      end
    end
    

    如果你真的想使用options_from_collection_for_select,你可以调整第三个参数,即text_method:你可以在你的FormCategory模型中定义一个formatted_name方法:

    class FormCategory < ActiveRecord::Base
      ...
      def formatted_name
        if inactive
          "#{name} (inactive)"
        else
          name
        end
      end
      ...
    end
    

    然后使用它:

    options_from_collection_for_select(FormCategory.all, :id, :formatted_name)
    

    【讨论】:

    • 这看起来非常适合将(非活动)附加到非活动选项!你知道如何只将非活动选项设置为红色吗?
    • 恐怕这是不可能的。另请参阅其他 SO 问题:stackoverflow.com/q/7208786/433940。您可以查看替代方案,例如 Select2,但无法在 &lt;select&gt; 中设置 &lt;option&gt;s 的样式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 2019-05-18
    • 2018-06-07
    相关资源
    最近更新 更多