Carla Dessi
Carla Dessi

Reputation: 9666

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?

Upvotes: 5

Views: 3220

Answers (2)

boulder_ruby
boulder_ruby

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

tomciopp
tomciopp

Reputation: 2742

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

Upvotes: 2

Related Questions