option_groups_from_collection_for_select
- 1.0.0 (0)
- 1.1.6 (0)
- 1.2.6 (0)
- 2.0.3 (38)
- 2.1.0 (-6)
- 2.2.1 (0)
- 2.3.8 (2)
- 3.0.0 (0)
- 3.0.9 (-3)
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (0)
- 4.1.8 (0)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (0)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- 7.2.3 (0)
- 8.0.0 (0)
- 8.1.1 (0)
- What's this?
option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)
public
Returns a string of option tags, like options_from_collection_for_select, but surrounds them with <optgroup> tags.
An array of group objects are passed. Each group should return an array of options when calling group_method Each group should return its name when calling group_label_method.
html_option_groups_from_collection(@continents, "countries", "continent_name", "country_id", "country_name", @selected_country.id)
Could become:
<optgroup label="Africa"> <select>Egypt</select> <select>Rwanda</select> ... </optgroup> <optgroup label="Asia"> <select>China</select> <select>India</select> <select>Japan</select> ... </optgroup>
with objects of the following classes: class Continent
def initialize(p_name, p_countries) @continent_name = p_name; @countries = p_countries; end def continent_name() @continent_name; end def countries() @countries; end
end class Country
def initialize(id, name) @id = id; @name = name end def country_id() @id; end def country_name() @name; end
end
NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
Wrapping with select tag
I didn’t knew how to wrap the output with <select> tag. I didn’t want to use raw html, but the doc doesn’t mention another way.
So, here is what I tried and it’s working:
<%= f.select :entry, option_groups_from_collection_for_select(@categories, :entries, :name, :id, :name) %>
I hope this helps anyone. :-)
How to include a “Please select…” (default/prompt) in a grouped dropdown list.
The clue here is that you actually specify the prompt on the select element, and not in the option_groups_from_collection_for_select element.
<%= f.select :post_type_id, option_groups_from_collection_for_select(@categories, :post_types, :name, :id, :name), :include_blank => "Please select..." %>
Hope this helps someone.

