问题
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