Rails 3 csv import to local database

May 30, 2012 |

I am a novice at best but this has worked for me multiple times so I figured I would share.

With Ruby 1.9.2, Fastercsv is a standard library so you no longer need to reference ‘fastercsv’ you can simply reference ‘csv’  (this is for older Ruby users)

The code is pretty straight forward:

namespace :db do
desc "load user data from csv"
 task :load_csv_data => :environment do
 require 'csv'
CSV.foreach("test_data.csv") do |row|
 :first_name => row[0],
 :last_name => row[1],
 :company => row[2],
 :address_one => row[3],
 :address_two => row[4],
 :address_city => row[5],
 :address_state => row[6],
 :address_zip => row[7],
 :phone => row[8],
 :transaction_date => row[9],
 :transaction_type => row[10],
 :lessor => row[11],
 :manufacturer => row[13],
 :model => row[14],
 :equipment_description => row[15],
 :equipment_serial_number => row[18],
 :transaction_value => row[19],
 :cost => row[20]


reference the csv file you want to import and run this inside its namespace: rake db:load_csv_data

hope this helps you out!

Leave a Reply