instance method
options_from_collection_for_select
Ruby on Rails 3.1.12
Since v2.2.3Signature
options_from_collection_for_select(collection, value_method, text_method, selected = nil)
Returns a string of option tags that have been compiled by iterating over the collection and assigning the the result of a call to the value_method as the option value and the text_method as the option text. Example:
options_from_collection_for_select(@people, 'id', 'name')
This will output the same HTML as if you did this:
<option value="#{person.id}">#{person.name}</option>
This is more often than not used inside a #select_tag like this example:
select_tag 'person', options_from_collection_for_select(@people, 'id', 'name')
If selected is specified as a value or array of values, the element(s) returning a match on value_method will be selected option tag(s).
If selected is specified as a Proc, those members of the collection that return true for the anonymous function are the selected values.
selected can also be a hash, specifying both :selected and/or :disabled values as required.
Be sure to specify the same class as the value_method when specifying selected or disabled options. Failure to do this will produce undesired results. Example:
options_from_collection_for_select(@people, 'id', 'name', '1')
Will not select a person with the id of 1 because 1 (an Integer) is not the same as ‘1’ (a string)
options_from_collection_for_select(@people, 'id', 'name', 1)
should produce the desired results.
Parameters
-
collectionreq -
value_methodreq -
text_methodreq -
selectedopt = nil
Source
# File actionpack/lib/action_view/helpers/form_options_helper.rb, line 338
def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
options = collection.map do |element|
[element.send(text_method), element.send(value_method)]
end
selected, disabled = extract_selected_and_disabled(selected)
select_deselect = {}
select_deselect[:selected] = extract_values_from_collection(collection, value_method, selected)
select_deselect[:disabled] = extract_values_from_collection(collection, value_method, disabled)
options_for_select(options, select_deselect)
end
Defined in actionpack/lib/action_view/helpers/form_options_helper.rb line 338
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionView::Helpers::FormOptionsHelper