Importing CSV data into your Rails app
Sometimes I need a quick way to import data into my databases. For this, I usually use two formats: XML or CSV. In Ruby, you can easily manipulate the two formats using existing libraries. In the case of XML, you can use the concept of builders. As for CSV you have the built-in CSV library or you can use fastcsv. In this article, I will show you how to import data in the CSV format into your Rails database.
If you are looking for a quick and dirty way you can do it as described in http://goodbadtech.com/2009/05/13/ruby-on-rails-import-csv-data-into-database/, which I will elaborate below:
require ‘csv’
CSV.open(‘your-csv-file.csv’, ‘r’).each do |row|
YourModel.create(:field1 => row[0], :field2 => row[1])
end
Here your-csv-file.csv is the name of the csv file that contains the data you wish to import. YourModel is the name of your model. For instance, if you are importing data into your Language model, then YourModel is Language. field1 and field2 are the names of your model’s fields, which are not required to have an order. row[0] and row[1] are the items found according to their position in the CSV line.
What this code will do is go throug each record (line) found in the CSV file and create an instance of that model in the database, using ActiveRecord. In order for this code to work you will need to fire up the Rails console like this:
rails console (if you are using Rails 3 or above)
ruby script/console (if you are using Rails 2.xxx or below)
And that’s basically it. This a quick and dirty way to import data into your Rails database using CSV. If you want a more complete solution, where you will be able to upload data from your browser, then have a look at this article http://goodbadtech.com/2009/05/13/ruby-on-rails-import-csv-data-into-database/
I am preparing another article that will show you how to import data from an Excel or ODF file.
Until then, hope this one was useful.
