Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a CSV file via a rake task?

Tags:

I know this question has been asked a lot on this forum but I'm under a strict deadline and I need some help, so any advice is much appreciated. I'm new to Ruby on Rails so please keep that in mind when responding. I want to create a rake task that, when run, updates multiple tables in mysqlite db. This is a migration file that creates a new incident in my db. How do I create a rake task that will input all this info via a CSV file. Can someone PLEASE give me some help in writing the rake file from start to finish. Obviously you don't need to write every task for every string, just give me a few examples. And besides the actual rake file, do I need to add code to any other part of my app (I know thats a very general question, but if I do need to add code, I would appreciate a general description of where). I feel a little bit of guidance will go along way. If anyone needs any more information from me please just ask.

class CreateIncidents < ActiveRecord::Migration   def self.up     create_table :incidents do |t|       t.datetime :incident_datetime       t.string :location       t.string :report_nr       t.string :responsible_party       t.string :area_resident       t.string :street       t.string :city       t.string :state       t.string :home_phone       t.string :cell_phone       t.string :insurance_carrier_name       t.string :insurance_carrier_street       t.string :insurance_carrier_city       t.string :insurance_carrier_state       t.string :insurance_carrier_phone       t.string :insurance_carrier_contact       t.string :policy_nr       t.string :vin_nr       t.string :license_nr       t.string :vehicle_make       t.string :vehicle_model       t.string :vehicle_year         t.timestamps     end   end    def self.down     drop_table :incidents   end end 
like image 247
RubyDude1012 Avatar asked Sep 17 '12 14:09

RubyDude1012


People also ask

How do I import a CSV file?

On the Data menu, point to Get External Data, and then click either Edit Text Import or Data Range Properties. If you select Edit Text Import, select the file that you imported originally, and then make changes to the external data in the Text Import Wizard.

What are the two different ways to import CSV module?

There are two ways to read data from a CSV file using csv . The first method uses csv. Reader() and the second uses csv. DictReader() .


1 Answers

under your project folder in lib/task create a rake file say "import_incidents_csv.rake"

follow this Ruby on Rails - Import Data from a CSV file

in rake file have following code

require 'csv' namespace :import_incidents_csv do   task :create_incidents => :environment do     "code from the link"     end end  

You can call this task as "rake import_incidents_csv:create_incidents"

like image 56
Rubyman Avatar answered Sep 24 '22 13:09

Rubyman