che*_*ell 5 ruby rubyzip ruby-on-rails-5
我有一个模型,其中一个附件使用ActiveStorage:
class ProofreadDocument < ApplicationRecord
has_one_attached :file
end
Run Code Online (Sandbox Code Playgroud)
我正在进行rake任务以将文件附加到proofread_document.这些文件被压缩成zip存档.
我知道我可以通过阅读ActiveStorage文档来附加以下文件:
@proofread_document.file.attach(io: File.open('/path/to/file'), filename: 'file.pdf')
Run Code Online (Sandbox Code Playgroud)
我的rake任务中有以下内容:
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
Run Code Online (Sandbox Code Playgroud)
这会产生以下错误:
NoMethodError: undefined method `read' for #<String:0x007f8d894d95e0>
Run Code Online (Sandbox Code Playgroud)
我需要一次读取每个文件的内容,以将它们附加到proofread_document实例.我怎样才能做到这一点?
通过将输入流包装在StringIO对象中,我能够成功完成如下工作:
self.file.attach(io: StringIO.new(zip_entry.get_input_stream.read), filename: zip_entry.name, content_type: MS_WORD_CONTENT_TYPE)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
276 次 |
| 最近记录: |