Reputation: 9666
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?
Upvotes: 5
Views: 3220
Reputation: 39695
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(""))}
Upvotes: 1
Reputation: 2742
Ryan Bates has a handy railscast on exactly this topic: http://railscasts.com/episodes/362-exporting-csv-and-excel
Upvotes: 2