Search code examples
ruby-on-railsrubyruby-on-rails-4simple-formcountry-codes

Ruby on Rails- Display Country Real Name with country-selector


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?


Solution

  • 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