One of my apps has to export data for the backend system to process it.
What’s the best way to create a CSV file in Rails and then return it as
a file to the client? i.e when they go to the link /csv/get_data it
would return a csv file.
I’ve been messing with the CSV library and I can get it to write out to
a file, but not sure how to best use this in a web app.
One of my apps has to export data for the backend system to process
it.
What’s the best way to create a CSV file in Rails and then return
it as
a file to the client? i.e when they go to the link /csv/get_data it
would return a csv file.
I’ve been messing with the CSV library and I can get it to write
out to
a file, but not sure how to best use this in a web app.
For me it’s easier not to generate a file on disk, and work only in
memory. This way I don’t have to worry about where to save the
temporary file, and then when to remove it.
If that makes sense in your application, to generate a CSV in-memory
you can do this:
def get_data
report = StringIO.new
CSV::Writer.generate(report, ‘,’) do |csv|
# csv << row for each row
end
report.rewind
send_data(report.read, :type => ‘application/csv;
charset=iso-8859-1’, :filename => ‘my_data.csv’)
end