使用wicked_pdf和rails ActiveJob编码错误

时间:2016-12-15 21:25:38

标签: ruby-on-rails actionmailer ruby-on-rails-5 wicked-pdf rails-activejob

我使用wicked-pdf来简化在我的Rails 5应用程序中生成pdf发票。我有两个动作利用了wicked-pdf的pdf功能。第一个操作生成pdf并将其呈现在新的浏览器窗口中。第二种方法将pdf附加到电子邮件中。

这两项行动都运作得很好。当我使用ActiveJob / Sidekiq将我的pdf邮件程序操作设置为'deliver_later'时,会出现此问题。当我添加'deliver_later'时,我会收到一条错误消息:

  

“\ xFE”从ASCII-8BIT到UTF-8

如果我使用“deliver_now”命令,则不会发生此错误。使用“deliver_now”发送电子邮件并正确附加PDF。

以下是我的邮件操作,邮件和工作的一些代码:

invoices_controller.rb

...
def create
  respond_to do |format|
    format.html do
      pdf = render_to_string( pdf: @order.ruling_invoice,
                          template: "orders/invoices/show.pdf.haml",
                          encoding: "utf8",
                          locals: { order: @order.decorate}
                        )
      SendInvoiceMailJob.new.perform( @order, pdf, @order.token )
      redirect_to order_url(id: @order.id, subdomain: current_company.slug),     notice: "This invoice has been emailed."
    end
  end
end
...

send_invoice_mail_job.rb

...
def perform( order, pdf, order_token )
  InvoiceMailer.send_invoice(order, pdf, order_token).deliver_later
end
...

invoice_mailer.rb

...
def send_invoice( order, pdf_invoice , invoice_token)
    @order = order
    attachments["#{invoice_token}.pdf"] = pdf_invoice
    mail(
    to: @order.email,
        from: @order.seller_email
    )
end
...

为什么此代码在send_invoice_mail_job.rb中使用“deliver_now”工作但是使用“deliver_later”无效?

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

您需要将 PDF 编译从邮件程序工作的外部移动到其中。因此,在您的控制器中,您可以执行以下操作:

SendInvoiceMailJob.new.perform(@order, @order.token)

然后在您的邮寄工作中,您可以:

def send_invoice(order, invoice_token)
    @order = order

    pdf = render_to_string(
      pdf: @order.ruling_invoice,
      template: "orders/invoices/show.pdf.haml",
      locals: { order: @order.decorate }
    )                        )

    attachments["#{invoice_token}.pdf"] = pdf_invoice
    mail(
    to: @order.email,
        from: @order.seller_email
    )
end

这样您就不会将 PDF 二进制文件传递到作业队列中。