简体   繁体   English

如何使用rubyzip将zip存档中的文件附加到ActiveStorage对象Rails 5

[英]How can I use rubyzip to attach files in a zip archive to an ActiveStorage object Rails 5

I have a model with one attachment that uses ActiveStorage: 我有一个带有使用ActiveStorage的附件的模型:

class ProofreadDocument < ApplicationRecord

  has_one_attached :file

end

I am working on a rake task to attach files to a proofread_document. 我正在执行一项rake任务,以将文件附加到proofread_document。 The files are compressed into a zip archive. 这些文件被压缩到一个zip存档中。

I understand that I can attach the files as follows from reading the ActiveStorage docs: 我了解可以通过阅读ActiveStorage文档来附加文件,如下所示:

@proofread_document.file.attach(io: File.open('/path/to/file'), filename: 'file.pdf')

I have the following in my rake task: 我的瑞克任务有以下内容:

    Zip::File.open(args.path_to_directory) do |zipfile|
          zipfile.each do |file|
            proofread_document = ProofreadDocument.new()
            proofread_document.file.attach(io: file.get_input_stream.read, filename: file.name)
            proofread_document.save
          end
     end

This produces the following error: 这将产生以下错误:

NoMethodError: undefined method `read' for #<String:0x007f8d894d95e0>

I need to read the contents of each file one at at time to attach them to the proofread_document instance. 我需要一次读取每个文件的内容,以将它们附加到proofread_document实例。 How can I do this? 我怎样才能做到这一点?

通过将输入流包装在StringIO对象中,我能够成功完成如下工作:

self.file.attach(io: StringIO.new(zip_entry.get_input_stream.read), filename: zip_entry.name, content_type: MS_WORD_CONTENT_TYPE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM