Savita.V.Malaghan
Savita.V.Malaghan

Reputation: 105

Ruby On Rails : Create csv-file and download as .zip-archive

Hi I have created csv file, I want to download that file in .zip-file in my rails application. Please help me. I am not able do this how to add that file to zip and download that zip-file. How to render that file in rails.

Below is the piece of code which I have tried,

     # method to create csv
     def to_csv
       CSV.generate do |csv|
         #build csv format of document
       end
     end

     # controller action to download zip
     def zip_download
       zip = Zip::File.open('document.zip', Zip::File::CREATE) do |zipfile|
               @documents.each do |document|
                # document.to_csv how to add this file .zip
               end
             end
       send_data zip, filename: "abc.zip", type: 'application/zip'
     end

Upvotes: 1

Views: 3801

Answers (1)

Jorge Sampayo
Jorge Sampayo

Reputation: 868

You can try:

zip.get_output_stream("#{yourcsvname}.csv") { |f| f.puts(yourdocument.to_csv) }

Check this question: Creating multiple csv-files and download all in one zip-archive using rails

I think that is what do you need.

Upvotes: 4

Related Questions