Search code examples
ruby-on-railsrubypostgresqlsidekiq

Sidekiq worker changing schema_search_path


I have the following worker:

class ImageWorker
  include Sidekiq::Worker

  def perform(tenant_id, id, key)
    tenant = Tenant.find(tenant_id)
    tenant.scope_schema do
      image = Image.find(id)
      unless image.image_processed?
        image.key = key
        image.remote_image_url = image.image.direct_fog_url(with_path: true)
        image.save!
        image.update_column(:image_processed, true)
      end
    end
  end
end

The Tenant#scope_schema method looks like this:

def scope_schema(*paths)
  original_search_path = ActiveRecord::Base.connection.schema_search_path
  paths << "extensions"
  ActiveRecord::Base.connection.schema_search_path = ["tenant#{id}", *paths].join(",")
  yield
ensure
  ActiveRecord::Base.connection.schema_search_path = original_search_path
end

When the ImageWorker job runs, it tells me that it can't find an Image with id=7 so the scope_schema doesn't appear to be working although I can take the same code outside of a Sidekiq worker class and it runs just fine.


Solution

  • Use after_commit to ensure the database record is there when the job executes.