58

I am using simple_form gem, I have a countries collection, it work fine when I select the country, and updated record will have the country id stored, but, when I try to edit the record, the chosen country is not selected by default at edit form.

Here is the code at edit form:

= f.input :country_id, :collection => all_countries

Shouldn't simple_form view the selected country from the db ?

simo
  • 23,342
  • 38
  • 121
  • 218
  • > Shouldn't simple_form view the selected country from the db ? It should because simple_form is just a wrapper around rails' form_for helpers. Check your generated html to see if there's no selected option in the code. – Ineu Feb 02 '12 at 07:13
  • I think it would be helpful if this question didn't use the term "default". When I see that I think that you're talking about what the selected item would be when you have selected nothing before, not when you had stored something and come back to the page. – cesoid May 18 '15 at 19:56
  • yea, I've fixed it, but the question got bit longer :) – simo May 21 '15 at 07:33
  • See http://stackoverflow.com/questions/6477942/rails-default-selected-radiobutton-in-simpleform-collection – mdwpilot Dec 17 '16 at 23:08

2 Answers2

136

Have you tried to use the :selected => option?

:selected => selected_country_id

So,

= f.input :country_id, :collection => all_countries, :selected => selected_country_id

This will work perfectly !!!

Cheers!

Manish Shrivastava
  • 30,617
  • 13
  • 97
  • 101
16

I know this has been answered, but I came here looking for a similar solution for a collection of check boxes. For posterity, here's how you do it:

<%= f.input :country_ids, :as => :check_boxes, :collection => [['USA', :USA], ['Japan', :JPN]], :checked => [:JPN], :include_hidden => false %>

Hope this helps someone.

genkilabs
  • 2,966
  • 30
  • 36