【问题标题】:Ruby on Rails- Display Country Real Name with country-selectorRuby on Rails - 使用国家选择器显示国家真实姓名
【发布时间】:2014-11-11 14:22:26
【问题描述】:

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

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

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

在用户展示页面上`

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

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

【问题讨论】:

  • 我没有使用 gem 但是如果你说&lt;%= @user.country.name %&gt;会发生什么?
  • 当输入 时,显示错误 undefined method `name' for "GB":String

标签: ruby-on-rails ruby ruby-on-rails-4 simple-form country-codes


【解决方案1】:

来自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

【讨论】:

  • 注意你现在必须说&lt;%= @user.country_**name** %&gt;
  • 我在输入 时遇到了同样的错误,错误是“GB”的未定义方法“名称”:字符串
  • @MarySmith 必须是 country_name,而不是 country.name
  • 更改 country_name 后,另一个错误我得到未定义的局部变量或方法 `country_code' 用于 #<0x007f9ee11e9bc8>
【解决方案2】:

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

需要在国家上调用.name方法来获取名字:

<%= @user.country.name %>

【讨论】:

【解决方案3】:

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

为了在你的用户模型中工作:

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

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

【讨论】:

    猜你喜欢
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多