Rails background worker always fails first time, works second

拈花ヽ惹草 提交于 2019-12-25 13:19:19

问题


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

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    

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.


回答1:


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

So rewrite it like this:

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

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.



来源:https://stackoverflow.com/questions/20820047/rails-background-worker-always-fails-first-time-works-second

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!