instance method options_from_collection_for_select

Ruby on Rails 7.1.6

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

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

collection req
value_method req
text_method req
selected opt = nil
Source
# File actionview/lib/action_view/helpers/form_options_helper.rb, line 401
      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 401 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::FormOptionsHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close