instance method
options_from_collection_for_select
Ruby on Rails 5.2.8.1
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 result of a call to the value_method as the option value and the text_method as the option text.
options_from_collection_for_select(@people, 'id', 'name') # => <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 actionview/lib/action_view/helpers/form_options_helper.rb, line 400
def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
options = collection.map do |element|
[value_for_collection(element, text_method), value_for_collection(element, value_method), option_html_attributes(element)]
end
selected, disabled = extract_selected_and_disabled(selected)
select_deselect = {
selected: extract_values_from_collection(collection, value_method, selected),
disabled: extract_values_from_collection(collection, value_method, disabled)
}
options_for_select(options, select_deselect)
end
Defined in actionview/lib/action_view/helpers/form_options_helper.rb line 400
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionView::Helpers::FormOptionsHelper