Vlad Balanescu Vlad Balanescu - 12 days ago 8
Ruby Question

Download all attachments in a model RAILS

I am using

rails4
with
paperclip
and
rails_admin
gems and I am trying to make a link which when clicked will download all the attachments from the submission table.

Here is my code

rails_admin/main/index.html.haml


- if @abstract_model.table_name == "submissions"
= link_to "Download all", '/downloadAttachments'


submission_controller.rb


# Download zip file of all submission
def download
@submissions = Submission.all

file = @submissions[0].file.url(:original, false) #folder to save the archive to

Zip::ZipFile.open(file, create=nil) do |zipfile|
@submissions.each do |filename|
zipfile.add(filename.file_file_name, filename.file.url(:original, false))
end
end
end


routes.rb


get '/downloadAttachments' => 'submissions#download'


When I click the link though, I get a message
Cannot find submission with id downloadAll
. From my experience with rails, that method should get called and create the downloadable zip for me. Question: what is wrong with this def and how can I get that zip downloaded?

[EDIT]

This code seems to work, but it's getting a:

File /files/submissions/files/45/original/file.pdf not found


But I can confirm that file definitely exists in my public folder

Answer

This is the solution:

submission_controller.rb

# Download zip file of all submission
  def download
    @submissions = Submission.all

    archiveFolder = Rails.root.join('tmp/archive.zip') #Location to save the zip

    # Delte .zip folder if it's already there
    FileUtils.rm_rf(archiveFolder)

    # Open the zipfile
    Zip::ZipFile.open(archiveFolder, Zip::ZipFile::CREATE) do |zipfile|
      @submissions.each do |filename|
        zipfile.add(filename.file_file_name, 'public/files/submissions/files/' + filename.id.to_s + '/original/' + filename.file_file_name)
      end
    end

    # Send the archive as an attachment
    send_file(archiveFolder, :type => 'application/zip', :filename => '2016 Submissions.zip', :disposition => 'attachment')
  end

routes.rb

get '/downloadAttachments' => 'submissions#download'

In the view then:

= link_to "Download All", '/downloadAttachments'