Rails 后台工作者总是第一次失败,第二次工作 [英] Rails background worker always fails first time, works second

查看:70
本文介绍了Rails 后台工作者总是第一次失败,第二次工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在保存对象后触发的 sidekiq 工作器:

I have a sidekiq worker that fires after an object is saved:

class Post < ActiveRecord::Base

  attr_accessible :description, 
                  :name,
                  :key 

  after_save :process

  def process
    ProcessWorker.perform_async(id, key) if key.present?
  end

  def secure_url
    key.match(/(.*\/)+(.*$)/)[1]
  end

  def nonsecure_url
    key.gsub('https', 'http')
  end

end

worker 如下所示(它还没有完成……只是在测试):

The worker looks like the following (it's not complete yet... just testing):

class ProcessWorker
  include Sidekiq::Worker

  def perform(id, key)

    post = Post.find(id)
    puts post.nonsecure_url

  end
end    

奇怪的是,每次 worker 触发时,它最初都会失败并显示以下错误:

Oddly enough, every time the worker fires, it initially fails with the following error:

undefined method `gsub' for nil:NilClass

但是,当工人稍后重试时 - 它总是成功.

But then, when the worker retries a bit later – it always succeeds.

感觉好像有些东西没有在它应该初始化的时候初始化......但我似乎无法追踪它.

It really feels as though something isn't initializing when it should... but I can't seem to track it down.

推荐答案

确保 process always true - 这是需要的一部分回调链.

Ensure that process always true - which is needed as part of the callback chain.

所以改写成这样:

def process
  ProcessWorker.perform_async(id, key) if key.present?
  true
end

当执行 ActiveRecord 回调链时,任何返回布尔值的方法都会影响该链 - false 将取消回调链.

When the ActiveRecord callback chain is being executed any methods that return a boolean will affect the chain - a false will cancel the callback chain.

这篇关于Rails 后台工作者总是第一次失败,第二次工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆