Ruby on rails &引用;无法打开条目进行阅读,而其打开用于写作“;在创建zip文件时

Ruby on rails &引用;无法打开条目进行阅读,而其打开用于写作“;在创建zip文件时,ruby-on-rails,zip,Ruby On Rails,Zip,我正在尝试创建一个函数来下载包含文件的zip文件。我接着说,如果你想下载CSV(我翻译了评论),我的代码应该如下所示: 下面是我如何修改代码的: class DownloadController < ApplicationController require 'zip' def zip # Creating zip file zip_tmp = File.new("#{Rails.root}/public/zip-#{Time.now.strftime('%d-%

我正在尝试创建一个函数来下载包含文件的zip文件。我接着说,如果你想下载CSV(我翻译了评论),我的代码应该如下所示:

下面是我如何修改代码的:

class DownloadController < ApplicationController
  require 'zip'

  def zip
    # Creating zip file
    zip_tmp = File.new("#{Rails.root}/public/zip-#{Time.now.strftime('%d-%m-%Y')}.zip", 'w+')
    FileDetail.all.each do |fichier|
      Zip::File.open(zip_tmp.path, Zip::File::CREATE) { |zipfile|
        # fichier.filename => file.mp3
        # fichier.path => path/to/file.mp3
        zipfile.get_output_stream(fichier.filename, fichier.path)
      }
    end

    send_file "#{Rails.root}/public/zip-#{Date.today.to_time}.zip"
  end
end
类下载控制器file.mp3
#fichier.path=>path/to/file.mp3
zipfile.get_输出_流(fichier.filename,fichier.path)
}
结束
发送文件“#{Rails.root}/public/zip-#{Date.today.to#u time}.zip”
结束
结束
然而,虽然我甚至不确定我是否正确地执行了此操作,但我得到了以下错误:
无法打开条目进行读取,而它是打开进行写入的
,目标是以下行:
Zip::File.open(Zip_tmp.path,Zip::File::CREATE){zipfile

有人能告诉我发生了什么事吗?我以前从来没有这样做过,所以我不知道出了什么问题

先谢谢你

FileDetail.all.each do |fichier|
  Zip::File.open(zip_tmp.path, Zip::File::CREATE) { |zipfile|
    # fichier.filename => file.mp3
    # fichier.path => path/to/file.mp3
    zipfile.get_output_stream(fichier.filename, fichier.path)
  }
end
这样做将尝试为FileDetail的每个成员创建zip文件。您应将其编码为仅打开并创建一次:

Zip::File.open(zip_tmp.path, Zip::File::CREATE) do |zipfile|
  FileDetail.all.each do |fichier|
    # fichier.filename => file.mp3
    # fichier.path => path/to/file.mp3
    zipfile.get_output_stream(fichier.filename, fichier.path)
  end
end

谢谢,我还必须将“get_output_stream”更改为“add”,但它现在可以工作了!
Zip::File.open(zip_tmp.path, Zip::File::CREATE) do |zipfile|
  FileDetail.all.each do |fichier|
    # fichier.filename => file.mp3
    # fichier.path => path/to/file.mp3
    zipfile.get_output_stream(fichier.filename, fichier.path)
  end
end