Import CSV directly to Database Rails 3.x

In case anyone likes to import .csv files, or you need to do some single
table exports through csv and then re-import them later on, you can use
the following code I created.

The first file is the rake file and the second file is the lib file.
The command to use is:

rake import_csv_file[“somefile.csv”’,“some_model”]

Make sure that the header rows of the CSV files you import are the names
of the fields. So, if you had a table with the following fields:

user_id, name, email, etc.

You would want the csv file to have user_id, name, email, etc. in the
first row cells. The lib class will automatically singularize and
constantize the model argument passed to the rake task and convert it
for you. So if you have a model called UserFile you would pass
user_file and it would automatically convert it to UserFile when
preceeding to upload it to the table.

I created an import folder in my rails root for importing the files,
since in this particular case, I’m the only one that’s importing. You
could expand upon this and alter the class to accept file uploads, etc.

Anyhoo, in case someone needs something quick and to the point, here it


RAKE File:

=> tasks/import_csv.rake

desc “Import a CSV using import_csv_file[‘file.csv’,‘model’]”
task :import_csv_file, :file, :model, :needs => :environment do |t,

p “Starting to import CSV data from #{args.file}.”
parse ="#{Rails.root}/import/#{args.file}",
p “Completed import successfully.”


RUBY lib file:

=> libs/import_csv.rb

class ImportCsv

attr_accessor :file, :model

def initialize(file,model)
@file = file
@model = model

require ‘csv’
def import
csv_text =
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
row = row.to_hash.with_indifferent_access