Rails:after_create回调的delayed_job?

时间:2013-12-27 15:07:10

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 delayed-job

有没有办法使用delayed_job gem在后台运行after_create模型回调函数?

我有一个private函数用作在用户注册后运行的回调after_create :get_geolocation

如何配置模型以在后台运行?

1 个答案:

答案 0 :(得分:9)

是的,您应该能够从ActiveRecord回调中排队delayed_job任务。致install and use delayed_job

  1. gem 'delayed_job_active_record'添加到Gemfile并运行bundle install
  2. 运行以下命令在数据库中创建delayed_job支持表:

    rails generate delayed_job:active_record

    rake db:migrate

  3. 在您的模型中:

  4. class MyModel < ActiveRecord::Base
      after_commit :get_geolocation, on: :create
    
      private
    
      def get_geolocation
      end
    
      handle_asynchronously :get_geolocation
    end
    

    请注意,您应该use after_commit instead of after_create to schedule your job,以避免在提交事务之前执行作业的情况。