I am trying to send multiple files to the browser. I cant call send_data for every record like in the code below because i get a double render error. According to this post i need to create the files and zip them so i can send them in one request.
@records.each do |r|
ActiveRecord::Base.include_root_in_json = true
@json = r.to_json
a = ActiveSupport::MessageEncryptor.new(Rails.application.config.secret_token)
@json_encrypted = a.encrypt_and_sign(@json)
send_data @json_encrypted, :filename => "#{r.name}.json" }
end
I am creating an array of hashes with the @json_encrypted
and the file_name
for each record. My question is how can i create a file for every record and then bundle them into a zip file to then pass that zip file to send_file
. Or better yet have multiple file download dialogs pop up on the screen. One for each file.
file_data = []
@records.each do |r|
ActiveRecord::Base.include_root_in_json = true
@json = r.to_json
a = ActiveSupport::MessageEncryptor.new(Rails.application.config.secret_token)
@json_encrypted = a.encrypt_and_sign(@json)
file_data << { json_encrypted: @json_encrypted, filename: "#{r.name}.json" }
end
So the issue i was having is that send_file
does not respond to an ajax call which is how i was posting to that action. I got rid of the ajax, and am sending the necessary data though a hidden_field_tag and submitting it with jquery. The code below creates files for the data, zips them, and passes the zip file to send_data.
file_data.each do |hash|
hash.each do |key, value|
if key == :json_encrypted
@data = value
elsif key == :filename
@file_name = value
end
end
name = "#{Rails.root}/export_multiple/#{@file_name}"
File.open(name, "w+") {|f| f.write(@data)}
`zip -r export_selected "export_multiple/#{@file_name}"`
send_file "#{Rails.root}/export_selected.zip", type: "application/zip", disposition: 'attachment'
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With