我正在使用国家宝石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] }
您需要传递哈希(
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] }
另一个选项是访问翻译,因为例如有时国家名称不是您想要的,例如:从“美利坚合众国”到“美国”
country_code = "US"
country_label = ::ISO3166::Country[country_code].data["translations"]["en"]
试试这个
ISO3166::Country.find_country_by_alpha2(country_code)&.name