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?
Yes, you should be able to enqueue a delayed_job task from an ActiveRecord callback. To install and use delayed_job:
gem 'delayed_job_active_record' to your Gemfile and run bundle install.Create the delayed_job support tables in your database by running:
rails generate delayed_job:active_record
rake db:migrate
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With