views:

45

answers:

1

Hello,

I have the following in my view to display a select box with countries in it:

@countries = {'United States' => 'US', 'France' => 'FR'} 
<%= select_tag 'countries', 
            options_for_select(@countries.to_a) %>

it works fine. Now in cases I have an error after submitting the form, all of the values in the text field that have been previously entered are shown again (so no need to re-enter them), but the select box is reset to its default value.

Any ideas what parameter should I include so when an error occurs a the value from the select box stays.

+1  A: 

Where do you store this value? If it is assigned to some model, then your form should look like this:

<% form_for @my_object do |f| %>
  # some fields
  <%= f.select 'country', options_for_select(@countries.to_a) %>
  # ...
<% end %>

Where country should be a field name where you store country in your model.

If you want to do it with select_tag (like your example), then you should pass to options_for_select another parameter:

select_tag 'countries', options_for_select(@countries.to_a, params[:countries])

Where params[:countries] should store currently selected country.

klew
Thank you @klew that is what I needed.
Adnan