Skip to content

Instantly share code, notes, and snippets.

@carlweis
Created January 11, 2016 10:29
Show Gist options
  • Save carlweis/ee544feb90d55a53efbe to your computer and use it in GitHub Desktop.
Save carlweis/ee544feb90d55a53efbe to your computer and use it in GitHub Desktop.
Import countries into rails app
require 'csv'
class CreateCountries < ActiveRecord::Migration[5.0]
def change
create_table :countries do |t|
t.string :code, null: false
t.decimal :latitude, {:precision => 10, :scale=>6}
t.decimal :longitude, {:precision => 10, :scale=>6}
t.string :name, null: false
t.boolean :active, null: false, default: false
t.timestamps
end
end
# seed database with countries from csv file
csv_text = File.read(Rails.root.join('db', 'csv', 'countries.csv'))
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
c = Country.new
c.code = row['code']
c.latitude = row['latitude']
c.longitude = row['longitude']
c.name = row['name']
c.save
puts "#{c.name}, #{c.code} saved!"
end
puts "Inserted #{Country.count} rows into the countries table"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment