Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 804
chell Avatar asked Oct 02 '18 10:10

chell


1 Answers

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)
like image 184
chell Avatar answered Oct 18 '22 03:10

chell