在我的Rails应用程序中,我安装了以下gem包:
gem 'countries'
gem 'country_select'
gem 'simple_form'
当用户注册时,他们会选择一个国家(例如英国)。
在用户的展示页面上:``
<%= @user.country %>` => Displays GB
我的问题是,如何将“英国”显示为完整名称?
在我的Rails应用程序中,我安装了以下gem包:
gem 'countries'
gem 'country_select'
gem 'simple_form'
<%= @user.country %>` => Displays GB
该宝石会自动与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
undefined local variable country_code
错误,那么你的代码(模型或控制器)中有地区代码country_code
。请检查一下。 - sebkkomdef country_name
country = ISO3166::Country[country_code]
country.translations[I18n.locale.to_s] || country.name
end
end
您需要安装"countries" gem和country_select gem。
@user.country
会返回一个国家对象,即一个Country类的实例。当你将其放在erb标签中时,Rails会尽力将其转化为字符串,并调用"to_s"方法。如果这个类定义了to_s方法,那么它将被返回 - 我猜测它确实有定义并且该方法返回国家代码。
要获取名称,你需要调用.country.name方法:
<%= @user.country.name %>
<%= @user.country.name %>
会发生什么? - sebkkom