class Snip < ApplicationRecord
after_create_commit :index_async
private
def index_async
Search::IndexSnipJob.perform_later(id)
end
end
module Search
class IndexSnipJob < ApplicationJob
queue_as :search
def perform(snip_id)
snip = Snip.find_by(id: snip_id)
return unless snip
SearchIndex.upsert(document_id: snip.id, body: { title: snip.title, content: snip.sanitized_content })
end
end
end
Enqueueing jobs inside a transaction can create “ghost jobs” when the transaction rolls back. Use after_commit or after_create_commit to enqueue work only after the DB commit succeeds.