我有一个form_categories
表,其中有一个名为active
的列,其类型为tinyint / boolean。如果表单类别记录的活动属性为true,则它处于活动状态。如果为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 %>
答案 0 :(得分: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
:您可以在formatted_name
模型中定义FormCategory
方法:< / p>
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)