【问题标题】:How to NOT send an email in ActionMailer when called from Sidekiq从 Sidekiq 调用时如何不在 ActionMailer 中发送电子邮件
【发布时间】:2015-11-14 10:49:19
【问题描述】:

我有一个邮件:

class MyMailer < ActionMailer::Base
  def send_something(user_id)

     return unless User.exists?(user_id)  #  <- the problem

     mail to: [...]
  end
end

从 Sidekiq 调用:

MyMailer.delay.send_something(id)

但是,如果在作业实际运行时 user_id 不存在,我只想返回而不发送任何电子邮件。但是 Sidekiq 不喜欢这样,会引发错误 (https://github.com/mperham/sidekiq/issues/2149)。

我应该怎么做 - 也许有一个我可以返回的虚拟/空 ActiveMailer 对象?

【问题讨论】:

  • 你的意思是return unless User.exists?(user_id)

标签: ruby-on-rails ruby actionmailer sidekiq


【解决方案1】:

您需要在创建作业之前确保用户存在。把代码改成这样:

MyMailer.delay.send_something(user.id) if user.persisted?

此外,您可能想要检查用户是否仍然存在并且在稍后运行作业时未被删除:

class MyMailer < ActionMailer::Base
  def send_something(user_id)
    user = User.find_by_id(user_id)

    if user
      mail to: [...]
    end
  end
end

【讨论】:

  • 但是我还需要在作业运行时检查用户是否存在 - 可能是它运行了 30 分钟或更长时间。
  • 嗨 - 我看不出有什么不同(我需要尝试一下) - 如果该方法没有返回任何内容,Sidekiq 邮件程序将会抛出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多