Skip to content

Instantly share code, notes, and snippets.

@marcomd
Last active May 18, 2023 18:42
Show Gist options
  • Save marcomd/a0eab74e59a8cd1ecc9e0f83d799f525 to your computer and use it in GitHub Desktop.
Save marcomd/a0eab74e59a8cd1ecc9e0f83d799f525 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.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
@sadfuzzy
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment