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 is.

Enjoy.