Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: delayed_job on an after_create callback? [closed]

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?

like image 253
Hopstream Avatar asked Jan 12 '23 14:01

Hopstream


1 Answers

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.

like image 112
Ash Wilson Avatar answered Jan 20 '23 20:01

Ash Wilson