Rails

How To Import Data From A CSV File In Rails Or Ruby

Posted by Weston Ganger on February 11, 2016

I needed to do some importing. CSV is the easiest format to work with for import data. Also if you didn’t know you can sometimes save your xls as a CSV for faster/easier access without additional gems.

Its built right into ruby you just need to require it.


require 'csv'

CSV.foreach(filename) do |row|
  Place.create({name: row[0], location: row[1], country: row[2]})
end

If you have columns headers in the file and they match the attribute names, you can do this slick method


CSV.foreach(filename, headers: true) do |row|
  Place.create(row.to_hash)
end


Related External Links:


Posted in Rails and Tagged with csv ruby rails 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts