Returns a string of <option></option> tags, like #options_from_collection_for_select, but groups them by <optgroup></optgroup> tags based on the object relationships of the arguments.
Parameters:
| collection: | An array of objects representing the <optgroup></optgroup> tags |
| group_method: | The name of a method which, when called on a member of collection, returns an array of child objects representing the <option></option> tags |
| group_label_method: | The name of a method which, when called on a member of collection, returns a string to be used as the label attribute for its <optgroup></optgroup> tag |
| option_key_method: | The name of a method which, when called on a child object of a member of collection, returns a value to be used as the value attribute for its <option></option> tag |
| option_value_method: | The name of a method which, when called on a child object of a member of collection, returns a value to be used as the contents of its <option></option> tag |
| selected_key: | A value equal to the value attribute for one of the <option></option> tags, which will have the selected attribute set. Corresponds to the return value of one of the calls to option_key_method. If nil, no selection is made. |
Example object structure for use with this method:
class Continent < ActiveRecord::Base has_many :countries # attribs: id, name end class Country < ActiveRecord::Base belongs_to :continent # attribs: id, name, continent_id end
Sample usage:
option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
Possible output:
<optgroup label="Africa"> <option value="1">Egypt</option> <option value="4">Rwanda</option> ... </optgroup> <optgroup label="Asia"> <option selected="selected" value="3">China</option> <option value="12">India</option> <option value="5">Japan</option> ... </optgroup>
Note: Only the <optgroup></optgroup> and <option></option> tags are returned, so you still have to wrap the output in an appropriate <select></select> tag.
Source Code
# File action_view/helpers/form_options_helper.rb, line 244 def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil) collection.inject("") do |options_for_select, group| group_label_string = eval("group.#{group_label_method}") options_for_select += "<optgroup label=\"#{html_escape(group_label_string)}\">" options_for_select += options_from_collection_for_select(eval("group.#{group_method}"), option_key_method, option_value_method, selected_key) options_for_select += '</optgroup>' end end
<code/>and<pre/>for code samples.