简体   繁体   English

如何自定义选项以获取完整的国家/地区名称作为 country_select gem 的值?

[英]How to customize options to get full country name as value of country_select gem?

I have used country_select gem, it working fine, now I want to set option value as full country name same as what it displayed in dropdown, not contry code.我使用了country_select gem,它工作正常,现在我想将选项值设置为与下拉列表中显示的完整国家名称相同的国家名称,而不是国家代码。

for eg: I am getting like below:例如:我得到如下:

<select id="order_ship_country" name="order[ship_country]">
    <option value="AU">Australia</option>
    <option value="CA">Canada</option>
    <option value="GB">United Kingdom</option>
    <option value="US">United States</option>
</select>

But I am expecting like this:但我期待这样:

<select id="order_ship_country" name="order[ship_country]">
    <option value="Australia">Australia</option>
    <option value="Canada">Canada</option>
    <option value="United Kingdom">United Kingdom</option>
    <option value="United States">United States</option>
</select>

Thanks in advance提前致谢

If you are using it in the User model, as explained from their doc , you create an instance method called country_name , that will return the country name of that user.如果您在User模型中使用它,如他们的 doc 中所述,您将创建一个名为country_name的实例方法,该方法将返回该用户的country name Also remember to replace country_code with the attribute of your User model, that you are using to store that country code.还要记住将country_code替换为您用于存储该国家/地区代码的User模型的属性。

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

then you use the select form helper然后你使用select表单助手

select("user", "country_code", User.all.collect {|u| [ u.country_name, u.country_code ] })

this should generate这应该产生

<select name="user[country_code]" id="user_country_code">
  <option value="AF">Africa</option>
  <option value="IT">Italy</option>
  <option value="FR">France</option>
</select>

1/ Make an initializer 1/ 做一个初始化程序

# config/initializers/country_select.rb

CountrySelect::FORMATS[:with_full_country_name] = lambda do |country|
  [
    country.name,
    country.alpha2,
    {
      'value' => country.name,
    }
  ]
end

2/ Call it in your view with format 2/ 在您的视图中使用format调用它

<%= country_select("user", "country", format: :with_full_country_name) %>

As explained in the documentation : https://github.com/stefanpenner/country_select#using-a-custom-formatter如文档中所述: https : //github.com/stefanpenner/country_select#using-a-custom-formatter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM