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">
 <optgroup label="Asia">

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


NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.

Show source
Register or log in to add new notes.
November 15, 2011 - (v3.1.0)
0 thanks

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. :-)

January 5, 2012 - (>= v3.0.9)
0 thanks

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.