2

I have a form_categories table which has a column called active which is of type tinyint/boolean. If the form category record's active attribute is true, then it is active. If false, then it is inactive.

I have a select box that displays all of the records within the form_categories table. I want to style the inactive form_category options red in order to convey to the user that that form_category is inactive. Or Even better, I'd like to put in parentheses next to each inactive form_category option: (inactive) in red letters.

Is this possible?

Below is my select box:

<%= 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 %>
Neil
  • 4,578
  • 14
  • 70
  • 155

1 Answers1

1

You can use options_for_select and provide the options hash yourself:

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

For form_categories_options, you can use a helper, like:

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

If you really want to use options_from_collection_for_select, you can tweak the third argument, namely the text_method: you can define a formatted_name method in your FormCategory model:

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

then use it:

options_from_collection_for_select(FormCategory.all, :id, :formatted_name)
linkyndy
  • 17,038
  • 20
  • 114
  • 194
  • This looks great for appending (inactive) to the inactive options! Do you know how to style only the inactive options red? – Neil Jan 19 '16 at 15:50
  • I'm afraid that's not possible. See also this other SO question: http://stackoverflow.com/q/7208786/433940. You may look at alternatives, such as Select2, but there is no way to style ` – linkyndy Jan 19 '16 at 16:02