Rails: Phone 号码 - 国际前缀

Rails: Phone numbers - international prefix

我正在使用国家 gem 和国家-select gem。

我的 phones table 中有一个名为:country_code 的属性。我要求用户在新的 phone 表单中选择他们的国家:

<%= f.input :country_code,  label: false, wrapper: :vertical_input_group  do %>
  <span class="input-group-addon">Country</span>
  <%= country_select("phone", "country_code", {priority_countries["AU", "GB", "NZ"], selected: "AU" }, class: "form-control" ) %>
<% end %>

我想拿下那个国家并获得国际前缀。

我有一个 phones 模型,我有:

def landline_number
   [international_code, area_code, phone_number].join('   ')
end

def international_code
   self.country_code = ISO3166::Country[country_code]
   country_code.translations[I18n.locale.to_s] || country_code.international_prefix
end

当我尝试时:

<%= @phone.landline_number %>

它打印国家名称而不是国际前缀。

如何让它打印数字而不是国家名称?

在我看来你的问题是这一行:

country_code.translations[I18n.locale.to_s] || country_code.international_prefix

根据文档示例

# Get a specific translation
c.translation('de') #=> 'Vereinigte Staaten von Amerika'
c.translations['fr'] #=> "États-Unis"

ISO3166::Country.translations             # {"DE"=>"Germany",...}
ISO3166::Country.translations('DE')       # {"DE"=>"Deutschland",...}

您实际上是先提取国家名称,因为它找到了代码

country_code.international_prefix

由于||未执行你有的条件。如果您要删除 || 左侧的代码它应该工作。换句话说,尝试像这样离开你的方法:

def international_code
    self.country_code = ISO3166::Country[country_code]
    country_code.international_prefix
end