Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fuzzygroup/7e9394bffc1c28b9ffe453d1276b90cb to your computer and use it in GitHub Desktop.
Save fuzzygroup/7e9394bffc1c28b9ffe453d1276b90cb to your computer and use it in GitHub Desktop.
Rails migration to add countries table and populate it with countries gem
require 'countries/iso3166'
class CreateCountries < ActiveRecord::Migration[6.0]
def change
create_table :countries do |t|
t.string :name, limit: 64
t.string :name_it, limit: 64
t.integer :region, limit: 1
t.string :iso2, limit: 2
t.string :phone_prefix, limit: 3
t.string :currency_code, limit: 5
t.boolean :eu_member, default: false
t.string :official_languages, array: true, default: []
t.timestamps
end
reversible do |dir|
dir.up do
%w(Europe Americas Asia Africa Oceania).each do |region|
h_countries = []
ISO3166::Country.find_all_countries_by_region(region).each do |c|
h_countries << {name: c.iso_short_name,
name_it: c.translations['it'],
region: region.downcase,
phone_prefix: c.country_code,
iso2: c.alpha2,
currency_code: c.currency_code,
official_languages: c.languages_official,
eu_member: c.data['eu_member'] }
end
Country.create(h_countries)
puts "Create #{h_countries.size} #{Country.model_name.human(count: h_countries.size)} regione #{region}"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment