Pergunta

Is there a way to use the delayed_job gem to run an after_create model callback function in the background?

I have a private function used as a callback after_create :get_geolocation that runs after a user signs up.

How could I configure the model to run that in the background?

Foi útil?

Solução

Yes, you should be able to enqueue a delayed_job task from an ActiveRecord callback. To install and use delayed_job:

  1. Add gem 'delayed_job_active_record' to your Gemfile and run bundle install.
  2. Create the delayed_job support tables in your database by running:

    rails generate delayed_job:active_record

    rake db:migrate

  3. In your model:

class MyModel < ActiveRecord::Base
  after_commit :get_geolocation, on: :create

  private

  def get_geolocation
  end

  handle_asynchronously :get_geolocation
end

Notice that you should use after_commit instead of after_create to schedule your job, so you avoid situations where the job executes before the transaction is committed.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top