preload and import a csv file into your rails 3 database
For a project I’m working on, there’s existing data that has to be in the database. The data exists in an excel spreadsheet which I then export as a CSV file. I then create the rake file lib/tasks/bootstrap.rake and place the following in it:
namespace :bootstrap do
desc "populate database with data from data1.csv"
task :default_data1 => :environment do
lines = File.new('public/data/data1.csv').readlines
header = lines.shift.strip
keys = header.split(',')
lines.each do |line|
params = {}
values = line.strip.split(',')
keys.each_with_index do |key,i|
params[key] = values[i]
end
Post.create(params)
end
end
desc "populate database with data from data2.csv"
task :default_data_2 => :environment do
lines = File.new('public/data/data2.csv').readlines
header = lines.shift.strip
keys = header.split(',')
lines.each do |line|
params = {}
values = line.strip.split(',')
keys.each_with_index do |key,i|
params[key] = values[i]
end
Post.create(params)
end
end
desc "Run all bootstrapping tasks"
task :all => [:default_data_1, :default_data_2]
end
I’m uploading two CSV files that I’ve moved to public/data/. The data looks something like this:
[csv]
title,content,author
foo,lorem ipsum,john doe
bar,ipsum lorem,jane doe
[/csv]
and as long as the first line in the csv matches the fields in your model, they’ll slip right in.
finally, run rake bootstrap:all to make the magic happen!
credits: this code is a mashup of these two little code snippits: one two
