Country Select
Currently, we see a text field for country_code when creating a gram.
Let's replace that with a select dropdown with actual country names.
1. Install Gem
Add to your Gemfile, and run bundle install in your terminal after that.
gem 'country_select'
2. Update new.html.erb
First, remove this line:
<%= f.text_field :country_code %>
In place of it, add this line:
<%= f.country_select :country_code, include_blank: true, priority_countries: ['SG', 'MY'] %>
Now, you have succcessfully replaced the text field for country_code with a select drop down.
When the form is submitted, it'll still be saving the 2-letters country code in the database.
3. Add a Helper
On our application, instead of showing country_code, we want to show the country name.
Let's add a helper in ApplicatioHelper to do this:
module ApplicationHelper
def country_name(country_code)
country = ISO3166::Country[country_code]
if country
country.translations[I18n.locale.to_s]
else
country_code
end
end
end
This method uses the ISO3166::Country class from the country_select gem
to find a country instance based on the country_code,
and since I18n.locale.to_s returns en (our language) by default,
this helper method will return the English name for the country code.
4. Add Helper to index.html.erb and show.html.erb.
In index.html.erb, let's use this method:
<div><%= country_name(gram.country_code) %></div>
In show.html.erb, let's use this method:
<div><%= country_name(@gram.country_code) %></div>
Restart the server and we are all done!