Persisting a Country Selection in Rails Using country_select
Rails’ country_select form helper doesn’t accept a :selected option. If a validation error occurs, you really don’t want to force the user to reselect a country. However, there’s no documented way of persisting that data when re-rendering an unvalidated form.
Fortunately, the country_select helper accepts a parameter called priority_countries. This exists so you don’t have to scroll all the way down past Uganda and Ukraine just to arrive at the good ol’ US of A. A clever workaround to this problem is to use the priority_countries parameter to effectively “select” the previous value through a bit of magic.
<%= form.country_select :country, [@location['country'] || 'United States'] %>
This ERb line merely appends your selected country to the top of the priority country list. And, indeed this allows your old country to remain selected even if a validation errors causes the form to be rendered again.
Trackbacks
Use this link to trackback from your own site.






nice! in somewhat related news, i’m learning to despise .net development.
See, I kind of want to learn .Net. I never really bothered doing Windows development before though. That will likely be one of those religions I may never get to practice.