Hi, 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. Hope someone can help... :) -- Posted via http://www.ruby-forum.com/.
On Mar 23, 2006, at 12:48, Pete wrote:> 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 -- fxn
Perfect! Thank you :) -- Posted via http://www.ruby-forum.com/.
Hi ! 2006/3/23, Pete <miggyx@peteslan.net>:> 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.There are two ways to do it. You can do as Xavier said and use the send_data trick, or just make your RHTML file look like CSV. I posted about both methods on my blog: http://blog.teksol.info/articles/2006/03/23/returning-csv-data-to-the-browser Hope that helps ! -- Fran?ois Beausoleil http://blog.teksol.info/