开发者

After the page is submited show the selected value in the select box ruby on rails

开发者 https://www.devze.com 2022-12-21 02:54 出处:网络
I have the following in my view to display a select box with countrie开发者_运维知识库s in it:

I have the following in my view to display a select box with countrie开发者_运维知识库s 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消