Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sadfuzzy/c5adb4df83538f0699802ffdf9cf5a7a to your computer and use it in GitHub Desktop.
Save sadfuzzy/c5adb4df83538f0699802ffdf9cf5a7a to your computer and use it in GitHub Desktop.
Rails migration to add countries table and populate it with countries gem
bundler add countries --version "~> 3.0.1" --require false
class Country < ApplicationRecord
enum region: { europe: 1, americas: 2, asia: 3, africa: 4, oceania: 5 }
end
require 'countries/iso3166'
class CreateCountries < ActiveRecord::Migration[7.0]
def change
create_table :countries do |t|
t.string :name, limit: 64
t.string :name_ru, 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_ru: c.translations['ru'],
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