如何将数据传递到通过Sidekiq发送的电子邮件模板

时间:2015-09-22 20:50:19

标签: ruby-on-rails ruby-on-rails-4 sidekiq

我在这个应用程序中使用Rails,Mongoid和Sidekiq。

在我的邮件程序中,我有以下内容:

def send_invoice(invoice, domain)
  @invoice = Invoice.find(invoice)
  @user = User.find(domain)
  attachments["invoice.pdf"] = File.read("#{Rails.root}/invoices/pdf/55f5c596019e2b51af000000-55f82b520540a78f43000000.pdf")
  mail to: "wagner.matos@mac.com", subject: "Invoice from MyJarvis", reply_to: @user.email, :from => @user.email, :bcc => 'wagner.matos@mac.com'
end

在我的电子邮件模板中,我有类似这样的内容(haml):

!!!
%html
  = "Hello #{@invoice[:name]}"

如果我使用ActiveMailer(不使用Sidekiq),一切正常。现在在我的工作人员中:

def perform(data, count)
  message = JSON.load(data)
  UserMailer.send_invoice(message['invoice'], message['domain']).deliver
end

然后我收到错误ActionView::Template::Error: undefined method '[]' for nil:NilClass

经过一番调查后,我发现问题出在电子邮件中使用的变量上。当我在不使用变量的情况下尝试使用相同的电子邮件时,一切正常。

现在我明白这是关于Sidekiq如何在Redis中存储数据的问题(作为json)。我不知道的是,如何使用Sidekiq将变量传递给电子邮件模板?

编辑:这是我的梅勒和我的工人:

邮件程序:

def send_invoice(invoice, domain)
  @invoice = Invoice.find(invoice)
  @user = User.find(domain)
  attachments["invoice.pdf"] = File.read("#{Rails.root}/invoices/pdf/55f5c596019e2b51af000000-55f82b520540a78f43000000.pdf")
  mail to: "email@example.com", subject: "Invoice", reply_to: @user.email, :from => @user.email
end

工人:

def perform(data, count)
  message = JSON.load(data)
  UserMailer.send_invoice(message['invoice'], message['domain']).deliver
end

在我的控制器中:

...
h = JSON.generate({ 'invoice' => @invoice.id.to_s, 'domain' => set_db })
PostmanWorker.perform_async(h, 1)
...

因为你可以看到我传递了id来让它在worker中处理而不是传递Hash。但是如何将@invoice哈希传递给电子邮件模板?

1 个答案:

答案 0 :(得分:0)

根据文档(https://github.com/mperham/sidekiq/wiki/Active-Job),有一种更新的语法(API)来传递电子邮件:

UserMailer.welcome_email(@user).deliver_later!(wait: 1.hour)

查看“Action Mailer”下的部分,因为这可以解决您的问题。