I'm trying to set the default value of a select tag
to the value that is saved in the model in active record
. At the same time, if no value is specified (e.g. on model-creation) I want a list
to be displayed to select a certain field of the select tag.
This is how I'd like to do it:
<% valid_years = Array.new %>
<% for i in 1900..Time.now.year %>
<% valid_years << i %>
<% end %>
<%= f.label t :label_year_of_birth %>
<%= f.select :year_of_birth, options_for_select(valid_years), class: "" %>
However, the value that's saved in active record is not displayed
in this select tag. Instead, the first value of the array is shown. Also, if I write options_for_select(valid_years, 1950)
, rails won't put the value to 1950.
However, if I use a simple text field tag
, rails WILL put the saved value in it.
<%= f.label t :label_year_of_birth %>
<%= f.text_field :year_of_birth, class: "" %>
Replace
<%= f.select :year_of_birth, options_for_select(valid_years), class: "" %>
With
<%= f.select :year_of_birth, options_for_select(valid_years, form_for_object_name.year_of_birth), class: "" %>
where
form_for_object_name
is the object that you are passing to your form since you didn't share the <%= form_for(?) do |f| %>
.
options_for_select
takes the second argument i.e. form_for_object_name.year_of_birth
as the selected
value.
If form_for_object_name.year_of_birth
is nil then select will default to the first value of your options i.e. 1900
in your case.