1

I have a form without a model backing it built using form_with in Rails 6:

<%= f.text_field :one %>

<%= f.select :two, [['Option 1',1],['Option 2',2]] %>

<%= f.submit 'Submit' %>

The only documentation I can find to set which of the select options are selected by default says that it will pre-select whatever is in the model. Since I don't have a backing model, how can I choose which option is selected? I've poked around the options a little and found nothing, but I do not necessarily know where to look.

RedBassett
  • 3,469
  • 3
  • 32
  • 56

1 Answers1

3

You must have missed it, there's an optional selected keyword argument.

Lastly, we can specify a default choice for the select box with the :selected argument:

<%= form.select :city, [["Berlin", "BE"], ["Chicago", "CHI"], ["Madrid", "MD"]], selected: "CHI" %>

Output:

<select name="city" id="city">
  <option value="BE">Berlin</option>  
  <option value="CHI" selected="selected">Chicago</option>
  <option value="MD">Madrid</option>
</select>

https://guides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease

magni-
  • 1,934
  • 17
  • 20
  • Thank you. I missed that, however I had tried a `selected` option with no luck. Looking again, it didn't work because I passed it in the `html_options` hash instead of the `options` hash! – RedBassett Jan 14 '21 at 04:10