Rails表单助手类维护州选中值异常:编辑时重置为Alaska
Got it, let's break down why this is happening and how to fix it. The core issue is that your options_for_us_state helper isn't using the saved state value from your training record to set the selected option. Without that, the browser just picks the first item in the list (Alaska) by default.
Step 1: Update the StatesHelper to support selected values
First, modify your helper method to accept a selected parameter, which we'll use to pass in the saved state code:
module Admin::StatesHelper STATES = [ ['Alaska', 'AK'], ['Alabama', 'AL'], ['Arkansas', 'AR'], ['American Samoa', 'AS'], ['Arizona', 'AZ'], ['California', 'CA'], ['Colorado', 'CO'], ['Connecticut', 'CT'], ['District of Columbia', 'DC'] ].freeze def options_for_us_state(selected_state = nil) # Use Rails' built-in helper to generate options with the correct selected value options_for_select(STATES, selected_state) end end
Rails' options_for_select does all the heavy lifting here—it takes your STATES array and automatically marks the option matching selected_state as selected.
Step 2: Pass the saved state to the helper in your form
Now, when rendering the state select in your edit form, you need to pass the existing state value from your training record.
If you're using a form builder (like with form_for or form_with), it would look like this:
<%= form_with(model: @training_record, namespace: :admin) do |f| %> <!-- Other form fields --> <div class="form-group"> <%= f.label :state, "State" %> <%= f.select :state, options_for_us_state(@training_record.state) %> </div> <%= f.submit "Update Training Record" %> <% end %>
If you're using a plain select_tag instead:
<%= select_tag "admin_training_record[state]", options_for_us_state(@training_record.state) %>
Quick Check: Make sure your data is stored correctly
Just to be safe, confirm that your training_records table's state column stores the two-letter state code (e.g., 'AK', 'CA') rather than the full state name. Your STATES array uses the code as the value, so this is required for the selected option to match properly.
That's it! Now when you load the edit form, the state select will show the saved state instead of defaulting to Alaska.
内容的提问来源于stack exchange,提问作者Jake

