Rails attach not working anymore - worked before

58 Views Asked by At

Situation

I have a model invoice with an attribute frozenn which handles archiving in my app. Upon archiving a PDF is supposed to get generated and attached (an outbound invoice in my app called out_invoice [submodel of invoice]) with the following callback:

  def store_physical_copy_on_freeze!
    unless physical_copy.attached? # without attachment attach current pdf permanently
      pdf_str = Home::OutInvoicesController.render(
        template: "home/out_invoices/pdf",
        layout: 'pdf',
        assigns:  {
          out_invoice: self,
          bank_account: company.mean_of_payment_for_invoices
        }
      )
      pdf = WickedPdf.new.pdf_from_string(pdf_str)
      # attach the currently live generated out invoice forever
      physical_copy.attach(io: StringIO.new(pdf), filename: "#{pdf_name}.pdf")
    end
  end

Problem:

After the method call is finished the attached PDF is not attached anymore (checked on console since it didn't appear in the frontend which it should).

I used byebug to debug that with following result: After the .attach call the physical_copy.attached? is true hence one has to assume it works but it doesnt.

This is not new code but old code which has been working before and I havent changed relevant configuration AFAIK. But of cause this might be the reason.

1

There are 1 best solutions below

0
Julian On

A friend (Rails expert) helped me to solve this. This method call was triggered in an after_save callback. It seems the models' callback retriggered the callback chain again or something (not fully understood the problem to be honest). He changed the callback from after_save to before_save which solved above problem. I would have never guessed also by looking at old code but the solution idea was right. Look at the history of changes. Voted the comment up of @dbugger !