Ruby on Rails-使用country-selector显示国家真实姓名

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

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

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

当用户注册时,他们选择一个国家(例如英国)

在用户的显示页面上

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

我的问题是,我如何将英国显示为全名?

ruby-on-rails ruby ruby-on-rails-4 simple-form country-codes
3个回答
4
投票

来自the countries gem's github page

此gem自动与country_select集成。它将更改其行为以存储alpha2国家/地区代码而不是国家/地区名称。

然后,来自country_selectgithub page

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

0
投票

@user.country将返回一个国家/地区对象,即类Country的实例。当你把它放在erb标签里面时,它会在它上面调用“to_s”,因为rails会尽力从对象中创建一个字符串。如果类定义了一个to_s方法,那么这就是返回的内容 - 我猜它确实如此,这个方法返回国家代码。

您需要在国家/地区调用.name方法以获取名称:

<%= @user.country.name %>

0
投票

我认为这个问题与这里缺少的宝石有关。

为此在您的用户模型中工作:

def country_name
    country = ISO3166::Country[country_code]
    country.translations[I18n.locale.to_s] || country.name
  end
end

您需要安装"countries" gem以及country_select gem。

© www.soinside.com 2019 - 2024. All rights reserved.