3

I need to save a PDF using wicked_pdf gem and Active Storage, unfortunately I haven't achieved it.

It is a very simple scenario, I need to create the PDF and save the object in the same process. The PDF is generated from a view.

@user = User.new(user_params)
view_string = render_to_string("user_pdf_view")
pdf = WickedPdf.new.pdf_from_string(view_string)
io_pdf = StringIO.new(pdf)

@user.pdf.attach(io: io_pdf,
                 filename: "user_filename",
                 content_type: 'application/pdf')

If the object isn't persisted, I get this error:

*** NameError Exception: uninitialized constant #<Class:0x00007ff6b30b3c98>::Analyzable
Did you mean?  ActiveStorage::Analyzer

And if the object is already saved, I get this one:

*** NoMethodError Exception: undefined method `build_after_unfurling' for #<Class:0x00007ff6b30b3c98>
enter code here

According to active storage docs, it is possible to attach an IO Object. I've also tried using a File and Tempfile instead of StringIO but with the same outcome.

I'm going through AS source code to see what's going on, but it would be great if someone has gone through this before and can help me up.

Thanks!


EDIT:

Update: I've just realized that if I change the config.eager_load to true... the error doesn't happen anymore.

Gerardo S
  • 187
  • 11
  • 1
    if the user is not persisted then the id is nil and you're actually passing `filename: ".pdf"` – max May 01 '20 at 00:49
  • 1
    Hey! You are right Max, but it doesn't solve the issue :/. Even if I hardcode the name of the file... the filename is not the issue. I'll update the question to remove this mistake – Gerardo S May 01 '20 at 03:12
  • 1
    @GerardoS wow, I just had this error and your solution of `config.eager_load to true` made it work. Can you please explain how you came up with this idea and why does it make it work? I'm trying to understand this weird case. Thank you. – Victor Martins May 06 '20 at 13:08
  • 2
    Hey @VictorMartins! Glad it helped you. The root cause I don't know yet, but the issue is that the class ActiveStorage::Blob is not loaded when it is required. I was having this issue while debugging with byebug, I was using a byebug breakpoint before this class could be loaded (lazy) by attaching a file, and this was causing the problem... Are you using any debugger? I managed to make it work correctly without eager_load: true, by moving the debugger after the attachment is made. I found a related issue but not exactly my case: https://github.com/rails/rails/issues/3547, maybe can help you – Gerardo S May 06 '20 at 17:33

0 Answers0