Reputation: 121
In my Rails application, I installed the following gems
gem 'countries'
gem 'country_select'
gem 'simple_form'
When a user signs up, they select a country (ex. United Kingdom)
on the User's Show page `
<%= @user.country %>` => Displays GB
My question is, how do I display United Kingdom as full name?
Upvotes: 4
Views: 4481
Reputation: 21
I believe the problem is to do with a missing gem here.
For this to work in your User model:
def country_name
country = ISO3166::Country[country_code]
country.translations[I18n.locale.to_s] || country.name
end
end
You need to have the "countries" gem installed as well as the country_select gem.
Upvotes: 0
Reputation: 1446
From the countries gem's github page:
This gem automatically integrates with country_select. It will change its behavior to store the alpha2 country code instead of the country name.
Then, from country_select
's github page
class User < ActiveRecord::Base
# Assuming country_select is used with User attribute `country_code`
# This will attempt to translate the country name and use the default
# (usually English) name if no translation is available
def country_name
country = ISO3166::Country[country_code]
country.translations[I18n.locale.to_s] || country.name
end
end
Upvotes: 5
Reputation: 32943
@user.country
will return a country object, ie an instance of class Country. When you put this inside the erb tag, it will have "to_s" called on it as rails tries its best to make a string out of an object. If the class defines a to_s method, then this is what is returned - i'm guessing it does and this method returns the country code.
You need to call the .name method on the country to get the name:
<%= @user.country.name %>
Upvotes: 0