Import CSV Using Rails Migration

Reposted from Rails Weenie:

Install FasterCSV (‘gem install fasterCSV’)

The code to use inside the migration is similar to:

FasterCSV.foreach(“#{RAILS_ROOT}/lib/symbols_database/security_list.csv“, :row_sep => “\r”) do |row|
field1,field2,field3 = row
Foo.create(:field1 => field1, :field2 => field2, :field3 => field3)
end

4 Responses to “Import CSV Using Rails Migration”

  1. Thank you for this. I needed to do exactly this and your post came in handy.

  2. [...] Whoops. So then I installed this wicked cool gem named FasterCSV and piggy-backed off of this migration import script and everything went great. So for all those people with ancient (and kinda useless) Excel data [...]

  3. [...] los tenía en CSV así que decidí seguir con ese mismo formato, busqué un poco y gracias a dotanything encontré FastCSV, una estupenda gema que nos facilitará el trabajo en general con archivos CSV, [...]

  4. I ran into the “no such file to load — faster_csv” and “no such file to load — fastercsv” errors when attempting to migrate.

    My solution was to add this to environment.rb:

    config.gem ‘fastercsv’, :lib => ‘faster_csv’

    Then run this from RAILS_ROOT:

    sudo rake gems:install

Leave a Reply