Method: ActionView::Helpers::FormOptionsHelper#options_from_collection_for_select
- Defined in:
- lib/action_view/helpers/form_options_helper.rb
#options_from_collection_for_select(collection, value_method, text_method, selected = nil) ⇒ Object
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:
(@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', (@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:
(@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)
(@people, 'id', 'name', 1)
should produce the desired results.
339 340 341 342 343 344 345 346 347 348 349 |
# File 'lib/action_view/helpers/form_options_helper.rb', line 339 def (collection, value_method, text_method, selected = nil) = 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) (, select_deselect) end |