simpleform和country_select with iso_codes

时间:2013-11-26 02:36:56

标签: ruby-on-rails ruby simple-form

我使用带有country_select的Ruby on Rails gem名为simple_form,我试图让下拉列表显示长国名,但将值设置为短iso代码。

如果我有以下

= f.input :country, priority: ["Australia", "United States", "New Zealand"]

然后我的优先国家之后的所有国家都是正确的(显示全名,同时使用iso_code作为值)。优先国家虽然使用名称作为标签&值。有没有办法在优先国家/地区设置ISO代码?

3 个答案:

答案 0 :(得分:1)

您可以设置

::CountrySelect.use_iso_codes = true

在初始化程序中全局使用ISO代码作为下拉值而不是国家/地区名称。

http://rubydoc.info/gems/country_select/1.3.1/frames

答案 1 :(得分:1)

只需将iso_codes: true传递到您的字段:

= f.input :country, priority: ["Australia", "United States", "New Zealand"], iso_codes: true

使用simple_form 3.1.0.rc2和country_select 1.3.1进行测试

答案 2 :(得分:0)

查看simple_form源代码是一个真正的PITA,因为它是如此令人难以置信的抽象。但从我所看到的情况来看,这似乎是使用CountrySelect Gem的问题。

gem说你应该使用iso_codes: true来确保代码被用作密钥。我想你将不得不深入研究如何处理priority参数或尝试将此选项传递给gem。

以下是相关代码:

  def country_options_for_select(selected = nil, priority_countries = nil, use_iso_codes = false)
    country_options = "".html_safe

    if priority_countries
      priority_countries_options = if use_iso_codes || ::CountrySelect.use_iso_codes
                                     priority_countries.map do |code|
                                       [
                                         ::CountrySelect::COUNTRIES[code],
                                         code
                                       ]
                                     end
                                   else
                                     priority_countries
                                   end

      country_options += options_for_select(priority_countries_options, selected)
      country_options += "<option value=\"\" disabled=\"disabled\">-------------</option>\n".html_safe
      #
      # prevents selected from being included
      # twice in the HTML which causes
      # some browsers to select the second
      # selected option (not priority)
      # which makes it harder to select an
      # alternative priority country
      #
      selected = nil if priority_countries.include?(selected)
    end

    values = if use_iso_codes || ::CountrySelect.use_iso_codes
               ::CountrySelect::ISO_COUNTRIES_FOR_SELECT
             else
               ::CountrySelect::COUNTRIES_FOR_SELECT
             end

    return country_options + options_for_select(values.sort, selected)
  end