How to import data from CSV files in Rails

posted on 14 May 2009 | Rails

CSV is commonly used to import data from an external source. You can populate your Rails applications with emails, user names, phone numbers etc. from other applications, databases, excel files... Let me show you an example.

#users.csv
kevin, kevin@gmail.com
Jhon, jhon@gmail.com
require 'csv'
CSV.open('users.csv', 'r').each do |row|
  User.create(:username => row[0], :email => row[1])
end

The open method, opens the specified file, parses lines from given stream and returns every line in an array. The diferent fields can be accessed by row[0], row[1] etc.

If you are a Windows user you must use rb as mode. The b option is the binary file mode needed in DOS/Windows environments.

The default separator is ','. You can use another separator passing it as a third parameter

CSV.open('users.csv', 'r', ';' )

More info www.ruby-doc.org/stdlib/libdoc/csv/rdoc/classes/CSV.html