Forum: Ruby on Rails Returning CSV data to the client

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Pete (Guest)
on 2006-03-23 13:48
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... :)
Xavier N. (Guest)
on 2006-03-23 14:18
(Received via mailing list)
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
Pete (Guest)
on 2006-03-23 17:41
Perfect!

Thank you :)
François B. (Guest)
on 2006-03-23 17:50
(Received via mailing list)
Hi !

2006/3/23, Pete <removed_email_address@domain.invalid>:
> 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/return...

Hope that helps !
This topic is locked and can not be replied to.