Rails 3 csv import to local database
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| Lead.create( :first_name => row, :last_name => row, :company => row, :address_one => row, :address_two => row, :address_city => row, :address_state => row, :address_zip => row, :phone => row, :transaction_date => row, :transaction_type => row, :lessor => row, :manufacturer => row, :model => row, :equipment_description => row, :equipment_serial_number => row, :transaction_value => row, :cost => row ) end end end
reference the csv file you want to import and run this inside its namespace: rake db:load_csv_data
hope this helps you out!