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
@marcomd
Copy link
Author

marcomd commented Sep 29, 2020

Add the gem countries to your gemfile without require, since it is only used to populate the table

# Countries is a collection of all sorts of useful information for every country in the ISO 3166 standard
gem 'countries', '~> 3.0.1', require: false

@marcomd
Copy link
Author

marcomd commented Sep 29, 2020

To create the rails model:
bin/rails g model Country name:string{64} name_it:string{64} region:integer{1} iso2:string{2} phone_prefix:string{3} currency_code:string{5}

Add the enum in the rails model:

class Country < ApplicationRecord
  enum region: {europe: 1, americas: 2,  asia: 3,  africa: 4, oceania: 5}
  # ...
end

@sadfuzzy
Copy link

👍

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