testa abalez testa abalez - 1 year ago 58
HTML Question

How to set a color for an option in a rails select form helper?

I search on the web, and it seems we can do it by apply a

style: "background-color:colorName;"
on the desired option.

But after many researches and tries, I cannot find how to do this with the rails form helpers.

This is what I have now :

<% users_array = ["Choose your player"] %>
<% users_array += User.all.map { |user| [user.name, user.id ]} %>
<%= select("player-#{user.id}-#{category[0]}", nil, options_for_select(users_array, user.name.to_s ), { }, { class: "selectstyle col-md-2" }) %>

I display all my model content with a default selected option specified in the
, but I want to add a different color to each users of my model displayed in this select.

The only example I found on the web are for a select without model displaying, and all my tries failed. How can I do ?

Answer Source

Check here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select

You can optionally provide HTML attributes as the last element of the array.

You can do something like:

users_array += User.all.map do |user|
  html_attributes = {}
  html_attributes['style'] = '...' if <some_condition>
  [user.name, user.id, html_attributes]