In a Rails form, how do f.select, options_for_select and f.collection_select differ, and how does each decide which option is selected?
answer
- choices as [text, value] pairs
- options hash third, HTML attributes fourth
- selected from the record, compared as strings
- a prebuilt option string skips auto-selection
- collection_select: value_method before text_method
basics
~20 sf.select takes choices such as [text, value] pairs and preselects the record's current value; options_for_select only renders option tags; f.collection_select builds options from records with a value method and a text method, also preselecting from the record.
solid answer
~40 s`f.select :country, [["Germany", "DE"], ["Japan", "JP"]]` writes `<select name="registration[country]">` and marks the option whose value equals `@registration.country`, compared as strings. Its third argument is select options (`include_blank:`, `prompt:`, `selected:`, `disabled:`) and its fourth is HTML attributes, so `class:` belongs in the fourth. `options_for_select(choices, selected)` is the lower-level helper that returns option tags; it suits `select_tag`, but passing its string to `f.select` means the record's value is no longer applied, so you must pass `selected` yourself. `f.collection_select :workshop_id, Workshop.order(:starts_at), :id, :title` reads records directly: the value method comes before the text method. `prompt:` appears only while the value is blank; `include_blank:` always adds an empty option.
code
erb · 12 lines<%= form_with model: @registration do |f| %>
<%= f.label :country %>
<%= f.select :country,
[["Germany", "DE"], ["Japan", "JP"], ["Kenya", "KE"]],
{ prompt: "Choose a country" },
{ class: "input" } %>
<%= f.label :workshop_id %>
<%= f.collection_select :workshop_id,
Workshop.order(:starts_at), :id, :title,
{ include_blank: "No workshop" } %>
<% end %>go deeper
Recall the shapes: [text, value] pairs for select, value method then text method for collection_select, and that the record's value is preselected.
Explain the options versus html_options split, prompt versus include_blank, and why a prebuilt options_for_select string loses automatic selection.
Spot the production bugs: reversed value and text methods writing titles into ids, missing preselection on edit pages, required selects with include_blank: false raising.
Judge when long or dynamic option lists should move to a search-backed control instead of a rendered select, balancing page weight against simplicity.
## Three helpers, three inputs A conference registration needs a country and a workshop. Rails offers three related helpers, and the difference is what you hand them: | Helper | Input | Returns | Preselects from the record | |---|---|---|---| | `f.select` | choices: strings, `[text, value]` pairs, a hash or grouped choices | a whole `<select>` | yes | | `options_for_select` | the same choices plus an optional selected value | only `<option>` tags | only what you pass | | `f.collection_select` | a collection plus value and text method names | a whole `<select>` | yes | ## `f.select` and its choices `f.select :country, choices, options = {}, html_options = {}` accepts: - **Strings**: `%w[DE JP]` uses each string as both text and value. - **Pairs**: `[["Germany", "DE"], ["Japan", "JP"]]` shows the first element and submits the last. - **A hash**: `{ "Germany" => "DE" }`, read the same way. - **Extra attributes**: a hash inside a pair, `["Japan", "JP", { data: { region: "apac" } }]`, becomes attributes on that option. - **Groups**: an array of `[group_label, [pairs]]` is detected and rendered with `<optgroup>`. The selected option is the one whose value, as a string, equals the record's current value, so an integer `3` matches the string `"3"`. `selected:` overrides that, and `disabled:` takes one value or an array of values to disable. ## Options versus HTML attributes The third and fourth arguments are the classic trap. The third is for the helper: `include_blank:`, `prompt:`, `selected:`, `disabled:`, `include_hidden:`. The fourth becomes attributes on `<select>`: `class:`, `data:`, `id:`. Writing `f.select :country, choices, class: "input"` puts `class` in the third hash, where it is ignored. Rails does move `required:`, `multiple:` and `size:` across if you put them in the wrong hash, which makes the rule look inconsistent. ## Blank choices 1. `include_blank: true` (or a string) always adds an empty option first. 2. `prompt: "Choose a country"` adds an empty-valued option only while the current value is blank, so an edit page with a saved country shows no prompt. `prompt: true` uses the `helpers.select.prompt` translation, "Please select" by default. 3. `required: true` on a single select forces a blank option, because an HTML required select needs an empty first choice; combining it with `include_blank: false` raises `ArgumentError`. ## `options_for_select` and its trap `options_for_select(container, selected = nil)` returns a string of `<option>` tags. It is the right tool with the model-less `select_tag`, or when you assemble options from several sources. But `f.select` returns a string argument unchanged, so `f.select :country, options_for_select(countries)` renders without consulting `@registration.country`, and nothing is preselected. Pass the value explicitly, `options_for_select(countries, @registration.country)`, or give `f.select` the raw choices. ## `f.collection_select` for records `f.collection_select :workshop_id, Workshop.order(:starts_at), :id, :title, prompt: true` calls `id` on each record for the option value and `title` for its text. The argument order (value method, then text method) is easy to reverse; reversed, the form submits titles into an integer column. Either argument can also be a lambda. Its tag-level sibling, `options_from_collection_for_select`, returns just the option tags for use with `select_tag`. ## Debugging a select that will not preselect 1. **Prebuilt options.** If the choices argument is a string from `options_for_select`, the record's value is ignored; pass `selected` to `options_for_select` instead. 2. **Stored value versus option value.** The record must hold the option's **value**, not its text: a country saved as `"Japan"` will never match an option valued `"JP"`. 3. **An explicit `selected:`.** `selected: nil` or a stale `selected:` in a shared partial overrides the record. 4. **Text and value swapped.** In `collection_select`, reversed methods produce options whose values are titles, which never equal an integer id. Comparison is by string, so a symbol, integer or string with the same characters all match; a type mismatch alone is rarely the cause. ## Multiple selection `multiple: true` appends `[]` to the select's name and adds a hidden empty value so that deselecting everything still submits the key; the resulting array always contains `""`.
- Why does an edit page with a saved country show no prompt option?`prompt:` is added only when the select's current value is blank. With a saved country, the record's value fills the selection and the prompt is skipped. Use `include_blank:` if an empty choice must always be available, for example to let the user clear the field.
- How do you build a select from records outside a form builder, for a filter form?Use `select_tag :workshop_id, options_from_collection_for_select(Workshop.all, :id, :title, params[:workshop_id])`. The tag helper needs prebuilt option tags, and the fourth argument marks the current filter value as selected, since there is no record to read it from.
- f.select :country, choices, class: "input" adds the class to the select element.
- In collection_select the text method comes before the value method.
- Passing options_for_select(list) to f.select still preselects the record's value.
- prompt: and include_blank: are two names for the same always-present blank option.
- The selected option is matched by object identity, so integers never match string values.