Kevin
Kevin

Reputation: 16043

Setting HTML options for <option> tags in select_tag

In the following ERB:

<%= form_for @my_model do |f| %>
  <%= f.select :my_attribute, options_from_collection_for_select(@my_options, :attribute, :name), {class: "select-style"} %>
<% end %>

The HTML options at the end will be applied to the generated <select> tag in the injected HTML. How can I supply HTML style options that will be applied to the injected <option> tags?

The Rails documention explains how to do this when using options_for_select, but not for when using options_from_collection_for_select.

Upvotes: 1

Views: 264

Answers (2)

Martin M
Martin M

Reputation: 8668

Interesting question. Where do you get the html options from?
Say, you want a static class for all options:

<%= f.select :my_attribute, options_from_collection_for_select(@my_options.map{|o| [o.attribute,{class: 'select-style'},o.name], :first, :last) %>

of cause, you can set the class from an attribute of my_option.

The trick is, that options_from_collection_for_select also extracts html options from each element (the Hash), so you have to construct the elements to include this hash.

But then, you can as well use options_for_select (as options_from_collection_for_select does internally):

<%= f.select :my_attribute, options_for_select(@my_options.map{|o| [o.name,{class: 'select-style'},o.attribute]) %>

Upvotes: 2

Shalev Shalit
Shalev Shalit

Reputation: 1963

In my opinion this option is unavailable. you can do this:

<%= options_from_collection_for_select(@my_options.map { |o| [o.attribute, o.name, { class: 'option-style' }] }, :first, :second) %> - but its ugly.

just do it with options_for_select:

<%= options_for_select(@my_options.map { |o| [o.attribute, o.name, { class: 'option-style' }] }) %>

Upvotes: 1

Related Questions