Search code examples
ruby-on-railssunspot

how to call after_commit(inject by sunspot) asynchronously


I'm using sunspot with rails. I know sunspot will use the after_commit hook to re-index... But if ever after_commit fails, the transaction rolls back and the Account(ActiveRecord::Base) I want to save is deleted.

I want to use sidekiq, perform_asyncto call the after_commit hook, but don't know how I can do that.

Any suggestions?


Solution

  •     module Reindex
          extend ActiveSupport::Concern
    
          def async_reindex
            AsyncIndexJob.perform_later(self.class.to_s, self.reload.id)
          end
    
          included do
            after_save :async_reindex
          end
        end
    
        class AsyncIndexJob < ActiveJob::Base
          queue_as :index
    
          def perform(*args)
            obj = args[0].constantize.find_by_id(args[1])
            if obj
              Sunspot.index obj
              Sunspot.commit
            end
          end
        end
    

    1.include Reindex module in ActiveRecord::Base

    2.set :auto_index => false

    3.all done

    AsyncIndex