在我的Rails应用程序中,我安装了以下gems
gem 'countries'
gem 'country_select'
gem 'simple_form'
当用户注册时,他们会选择一个国家(例如英国)
在用户的显示页面`
<%= @user.country %>` => Displays GB
我的问题是,如何将英国显示为全名?
来自国家gem的github页面:
此宝石自动与country_select集成。它将改变其行为以存储alpha2国家代码而不是国家名称。
然后,从country_select
的github页面
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
@user.country
将返回一个country对象,即类country的实例。当你把它放在erb标记中时,它会调用"to_s",因为rails会尽力从对象中生成一个字符串。如果这个类定义了一个to_s方法,那么这就是返回的内容——我猜它是这样做的,这个方法返回国家代码。
您需要在国家/地区调用.name方法才能获得名称:
<%= @user.country.name %>
我认为问题在于这里缺少一个gem。
为了在您的用户模型中工作:
def country_name
country = ISO3166::Country[country_code]
country.translations[I18n.locale.to_s] || country.name
end
end
您需要安装"countries"gem以及country_select gem。