Forked from marcomd/rails_migration_create_countries.rb
Last active
May 18, 2023 18:45
-
-
Save sadfuzzy/c5adb4df83538f0699802ffdf9cf5a7a to your computer and use it in GitHub Desktop.
Rails migration to add countries table and populate it with countries gem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bundler add countries --version "~> 3.0.1" --require false |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Country < ApplicationRecord | |
enum region: { europe: 1, americas: 2, asia: 3, africa: 4, oceania: 5 } | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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