ruby - 如何使用 rubyzip 将 zip 存档中的文件附加到 ActiveStorage 对象 Rails 5
问题描述
我有一个带有一个使用 ActiveStorage 的附件的模型:
class ProofreadDocument < ApplicationRecord
has_one_attached :file
end
我正在执行一项将文件附加到校对文档的 rake 任务。这些文件被压缩到一个 zip 存档中。
我知道我可以通过阅读 ActiveStorage 文档来附加以下文件:
@proofread_document.file.attach(io: File.open('/path/to/file'), filename: 'file.pdf')
我的 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
这会产生以下错误:
NoMethodError: undefined method `read' for #<String:0x007f8d894d95e0>
我需要一次阅读每个文件的内容,以将它们附加到 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)
推荐阅读
- python - 构造一个赋值矩阵 - Python
- python - Pandas - 同一列中的不同时间格式
- npm - 纱线不再存在
- mule - mule 自定义策略配置中的 Dataweave 代码
- asp.net-core - 如何将 int 映射到布尔 mvc core2.1
- javascript - X11 xorg Electron App cant open in fullscreen
- mysql - Ruby on Rails 和查询(理解问题)
- sql-server - 在 sql server 2016 的 where 子句中读取 json 值
- android - BluetoothAdapter.LeScanCallback 未找到 BLE 设备
- java - Redshift - 选择查询表名在双引号中不起作用