Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting to CSV in Rails

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?

like image 408
Carla Dessi Avatar asked Oct 23 '22 12:10

Carla Dessi


2 Answers

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

like image 82
tomciopp Avatar answered Oct 30 '22 23:10

tomciopp


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(""))}
like image 32
boulder_ruby Avatar answered Oct 31 '22 00:10

boulder_ruby