5

I need to export everything from one table into a CSV file, I've used the faster CSV gem before, but it stopped working with newer versions of rails. Does anyone have another way i could use?

Carla Dessi
  • 9,086
  • 9
  • 39
  • 53
  • possible duplicate of [Export data to CSV in rails](http://stackoverflow.com/questions/4302050/export-data-to-csv-in-rails) – Romain Aug 21 '12 at 10:44

2 Answers2

2

Ryan Bates has a handy railscast on exactly this topic: http://railscasts.com/episodes/362-exporting-csv-and-excel

tomciopp
  • 2,602
  • 2
  • 31
  • 60
1

To convert an active record database to csv just from the console (w/o a controller or view) directly to a file would be something like this

tags = [Model.column_names]
rows = tags + Model.all.map(&:attributes).map(&:to_a).map { |m| m.inject([]) { |data, pair| data << pair.last } }
File.open("ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join(""))}
boulder_ruby
  • 38,457
  • 9
  • 79
  • 100