iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 29
1
Modern Web

Ruby礦工的Rails地圖系列 第 29

實用Gem介紹:country_select

  • 分享至 

  • twitterImage
  •  

倒數第二天
來介紹方便的國籍下拉套件:
country_select

Gemfile

gem "country_select"

然後bundle後就可以使用囉

= f.country_select

在model的地方顯示可以這樣做
app/models/user.rb

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

有一些進階的選項可以做,比方說:
不能空白 include_blank: false
建議選項放在前面 priority_countries: ["TW", "HK"]

台灣的country顯示為

> ISO3166::Country[:TW].name
=> "Taiwan, Republic of China"

但我自己是很不喜歡這個顯示,所以順便示範一下修改預設顯示
在選擇的地方可以加上format

#config/initializers/country_select.rb
CountrySelect::FORMATS[:with_alpha2] = lambda do |country|
  name = country.alpha2 == "TW" ? "台灣" : country.name
  "#{name} (#{country.alpha2})"
end

重啟server 以後

= p.country_select :nation, [ "TW","HK" ], format: :with_alpha2

選項就可以顯示為「台灣」了

在顯示部分
因為存入的是兩碼的國碼「TW」,可以修改如下:

#app/models/user.rb
def country_name
    if nation == "TW"
      "台灣(TW)"
    else
      country = ISO3166::Country[nation]
      country.translations[I18n.locale.to_s] || country.name
    end
end

題外話,rails 2.2以前是有內建country_helper的
但因為台灣的國際地位問題(ISO3166台灣定義為中國的一省)
為了維持中立,所幸移除
相關經過請見ihower的記錄
希望有朝一日,台灣能有自己的國家
感謝大家


上一篇
實用Gem介紹:i18n-js
下一篇
30天鐵人賽回顧總整理暨心得 - 心中的紅寶石
系列文
Ruby礦工的Rails地圖30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言