【问题标题】:Resque not recognising instance variablesResque 无法识别实例变量
【发布时间】:2015-09-12 05:26:00
【问题描述】:

我正在使用 resque 发送电子邮件。如果我的邮件模板包含对实例变量的任何引用,则不会发送电子邮件。在我使用 resque 将其移动到后台作业之前,激活邮件程序正常工作。

users_controller.rb

def create
  @user = User.new(user_params)
  if @user.save
    Resque.enqueue(SendActivationEmail, @user.id)
    flash[:info] = "Please check your email to activate your account."
    redirect_to root_url
  else
    render 'new'
  end
end

send_activation_email.rb

class SendActivationEmail
  @queue = :email_queue
  def self.perform(user_id)
    user = User.find(user_id)
    UserMailer.account_activation(user).deliver_now
  end
end

user_mailer.rb

class UserMailer < ApplicationMailer
  def account_activation(user)
    @new_user = user
    mail to: user.email, subject: "Account activation"
  end
end

account_activation.text.erb

Hi,

Welcome. Click on the link below to activate your account:

<%= edit_account_activation_url(@new_user.activation_token, email: @new_user.email) %>

resque web中记录的错误是: 没有路由匹配 {:action=>"edit", :controller=>"account_activations", :email=>"user5@domain.com", :id=>nil} 缺少必需的键:[:id]

删除链接后会发送以下内容...

account_activation.text.erb

Hi,

Welcome. Click on the link below to activate your account:

路线正确:

edit_account_activation GET    /account_activations/:id/edit(.:format)                             account_activations#edit

【问题讨论】:

  • 您是否使用设备进行用户管理(如激活令牌)
  • 错误在&lt;%= edit_account_activation_url(@new_user.activation_token, email: @new_user.email) %&gt;行,发给你rake routes输出
  • 路由是正确的,因为在我实施 resque 之前激活电子邮件工作正常。
  • 从等式中取出链接。模板根本无法识别实例变量。
  • @user1567212 正如你所说的实例变量,我相信你没有将它存储在数据库中?但它是自动生成的。

标签: ruby-on-rails resque


【解决方案1】:

只是为了确保,稍微更改您的user_mailer.rb 以使用@new_user 实例变量在account_activation 方法中检索它的电子邮件。

class UserMailer < ApplicationMailer
  def account_activation(user)
    @new_user = user
    mail to: @new_user.email, subject: "Account activation"
  end
end

在您的 config/environments/development.rb 文件中,添加:

config.action_mailer.raise_delivery_errors = true

如果电子邮件发送有任何错误,这将通知您。您将能够查看您的开发日志。

试试这两件事,让我知道更新。收到您的反馈后,我会更新我的答案。

更新

当你说:The activation mailer worked correctly before I moved it to a background job using resque. 你是什么意思?你在生产模式下测试过吗?还是处于开发模式?在开发模式下,我认为不会发送实际的电子邮件,但您可以预览它(在 Rails 4.1.x 中)。当您进入生产环境时,您需要设置一个外部服务器来发送实际的电子邮件。

但是,添加:

config.action_mailer.raise_delivery_errors = true

按照我上面的建议在您的config/environments/development.rb file 中,然后您将能够查看电子邮件传递是否有任何错误。然后,您可以进行下一步。希望这会有所帮助。

【讨论】:

  • 正在生产中。问题最终是模板无法访问实例变量。我问了另一个问题,首先检查我的设置是否正确。我发现这意味着工人可能存在问题:stackoverflow.com/questions/9335327/…
【解决方案2】:

问题在于实例变量从基于符号的键转换为基于字符串的键。在我的邮件视图中,我通过符号获取值,因此可以通过字符串获取值,或者调用 hash.symbolize_keys!转换回符号键。

我找到的解决方案来自:https://github.com/zapnap/resque_mailer/issues/23

【讨论】:

    猜你喜欢
    • 2016-09-14
    • 1970-01-01
    • 2021-02-27
    • 2013-05-15
    • 2013-01-16
    • 2014-06-10
    • 2017-01-04
    • 2013-08-13
    • 2018-11-12
    相关资源
    最近更新 更多