Rails: How to generate basic option tags


I’ve compiled a guide on generating options tags using options_for_select.

Environment

  • Ruby 2.2.3
  • Rails 4.2.5

options_for_select

This method generates option tags from arrays or hashes. Even without knowing options_from_collection_for_select, you can create option tags with this.

Basics

When passing a simple array, the array elements become the option values.

You can set an initial value by passing the selected value as the second argument.

To select multiple values, pass an array of selected values.

Separating Value and Display

When setting the value attribute of each option tag separately, use arrays or hashes to pass the value and display name. For arrays, place the display name in the first element and the value in the second. For hashes, set the display name as the key and the value as the value.

To set a selected option, use the same method as before, passing the value(s) in the second argument.

Adding HTML Attributes

To add HTML attributes, insert a hash into each option element in the array.

While there may be ways to pass options using hashes, the official API documentation states arrays, so we use arrays. These HTML attributes are extracted from the array using option_html_attributes.

If you pass ["a", ["b", "c"]] as the first argument, element will receive "a" and ["b", "c"]. If you pass {a: 1, b: 2} as a hash, element will receive ["a", 1] and ["b", 2].

Specifying Unavailable Options

Similar to setting an initial value, here we set the disabled value in a hash to specify options that should be disabled.

The last argument can only be selected or disabled. This final argument is processed by extract_selected_and_disabled inside options_for_select.