I have a model with one attachment that uses ActiveStorage:
class ProofreadDocument < ApplicationRecord
has_one_attached :file
end
I am working on a rake task to attach files to a proofread_document. The files are compressed into a zip archive.
I understand that I can attach the files as follows from reading the ActiveStorage docs:
@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. How can I do this?
I was able to succeed by wrapping the input stream in a StringIO object as follows:
self.file.attach(io: StringIO.new(zip_entry.get_input_stream.read), filename: zip_entry.name, content_type: MS_WORD_CONTENT_TYPE)
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