将 Alpha2 国家/地区更改为真实国家/地区名称

问题描述 投票:0回答:3

我正在使用国家宝石https://github.com/hexorx/countries并尝试从alpha2国家/地区名称中获取国家/地区名称。但它以[object object]的形式出现。这是我的代码。

render :json => @countries.map { |c| [c.id, ::ISO3166::Country[c.country]] }

这将按预期返回 aplha2 罚款,它保存在国家/地区列中:

render :json => @countries.map { |c| [c.id, c.country] }
ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1
3个回答
4
投票

您需要传递哈希(

data
)而不是
Country
实例。

render :json => @countries.map { |c| [c.id, ::ISO3166::Country[c.country].data] }

如果您只想要国家/地区名称,请使用

name
:

render :json => @countries.map { |c| [c.id, ::ISO3166::Country[c.country].name] }

0
投票

另一个选项是访问翻译,因为例如有时国家名称不是您想要的,例如:从“美利坚合众国”到“美国”

country_code = "US"
country_label = ::ISO3166::Country[country_code].data["translations"]["en"]

0
投票

试试这个

ISO3166::Country.find_country_by_alpha2(country_code)&.name
© www.soinside.com 2019 - 2024. All rights reserved.