Search code examples
ruby-on-railscallbacksidekiq

Sidekiq can not find object with ID when worker is calling from after_save callback


class ContactEmail < ActiveRecord::Base
  after_save :check_existence_of_user

  private

  def check_existence_of_user
    ContactEmailCheckWorker.perform_async(id)
  end
end

class ContactEmailCheckWorker
  include Sidekiq::Worker
  sidekiq_options queue: :background_job

  def perform(contact_email_id)
    # sleep 1.seconds
    ce = ContactEmail.find(contact_email_id)
    # ....
  end
end

I have this error:

Couldn't find ContactEmail with 'id'=426

But after sidekiq try again this job and it's ok, find it. When I uncomment sleep it's working. Where is the problem? Transaction problem with after_ callback?


Solution

  • You need use after_commit callback. More information.

    Example:

    class ContactEmail < ActiveRecord::Base
      after_commit :check_existence_of_user