RedBassett
RedBassett

Reputation: 3587

Rails form_with select selected option

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.

Upvotes: 2

Views: 8441

Answers (1)

magni-
magni-

Reputation: 2055

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

Upvotes: 5

Related Questions