Ruby on Rails - 使用国家选择器显示国家真实名称

4

在我的Rails应用程序中,我安装了以下gem包:

gem 'countries'
gem 'country_select'
gem 'simple_form'

当用户注册时,他们会选择一个国家(例如英国)。
在用户的展示页面上:`

`
<%= @user.country %>` => Displays GB

我的问题是,如何将“英国”显示为完整名称?

1
我没有使用过这个 gem,但是如果你输入 <%= @user.country.name %> 会发生什么? - sebkkom
当输入 <%= @user.country.name %> 时,出现错误 undefined method `name' for "GB":String。 - Mary Smith
3个回答

5

来自该国宝石的GitHub页面

该宝石会自动与country_select集成。它将改变其行为,以存储alpha2国家代码而不是国家名称。

然后,从country_selectgithub页面来看

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

1
在我更改了country_name之后,我遇到了另一个错误:undefined local variable or method `country_code' for #User:0x007f9ee11e9bc8。 - Mary Smith
@MarySmith,能否告诉我你是如何解决这个问题的?我意识到你可能已经在聊天中想出了解决方案。 - Benjamin
如果你遇到了undefined local variable country_code错误,那么你的代码(模型或控制器)中有地区代码country_code。请检查一下。 - sebkkom
@Mel,你的Gemfile文件中是否同时拥有countries和country_select两个宝石? - Timmy Von Heiss
@TimmyVonHeiss - 是的 - Mel
显示剩余11条评论

0
我认为问题与此处缺少的 gem 有关。
为了让它在您的用户模型中工作:
def country_name
    country = ISO3166::Country[country_code]
    country.translations[I18n.locale.to_s] || country.name
  end
end

您需要安装"countries" gem和country_select gem。


0

@user.country会返回一个国家对象,即一个Country类的实例。当你将其放在erb标签中时,Rails会尽力将其转化为字符串,并调用"to_s"方法。如果这个类定义了to_s方法,那么它将被返回 - 我猜测它确实有定义并且该方法返回国家代码。

要获取名称,你需要调用.country.name方法:

<%= @user.country.name %>

你使用的是哪个宝石(gem)?我以为是这一个 https://github.com/hexorx/countries ,但听起来不一样。 - Max Williams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接