rails, simple_form, how to set selected index of a collection when page loaded?

Ruby on-RailsRuby on-Rails-3Simple Form

Ruby on-Rails Problem Overview


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 ?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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!

Solution 2 - Ruby on-Rails

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsimoView Question on Stackoverflow
Solution 1 - Ruby on-RailsManish ShrivastavaView Answer on Stackoverflow
Solution 2 - Ruby on-RailsgenkilabsView Answer on Stackoverflow