【问题标题】:Rails callbacks not working when create/update/destroy records using background jobs使用后台作业创建/更新/销毁记录时,Rails 回调不起作用
【发布时间】:2017-10-05 10:00:47
【问题描述】:

我正在使用 sidekiq-limit_fetch(带有 redis)gem 进行后台处理。我有以下模式和回调

class Modal < ApplicationRecord

  # ======== Callbacks ==============================
  after_create :add_activity


  def add_activity
    p 'came here ************'
    p 'came here ************'
    #  Do some operations here  
  end

end

我的工作如下

class ActivityWorker
  include Sidekiq::Worker

  # TODO - Update goal satisfied people
  def perform(campaign_id)
    Modal.create(data: data)
  end
end

我可以看到表中添加了一些记录,但未调用 after_create 回调。我认为回调只会在使用模型/控制器创建/更新/销毁时起作用。我是赖特吗?如果是,请建议我以其他方式使用回调作业。

【问题讨论】:

  • 回调应该在这种情况下触发。还有其他问题。
  • 为什么你认为回调没有被触发?后台工作人员的登录可能设置不同,因此您可能不会在日志中看到它。

标签: ruby-on-rails


【解决方案1】:

我建议你写service来调用或者自己写方法,尽量少用callback。

这是我的服务方式示例

服务/create_modal_service.rb

class CreateModalService
  def self.create(params={})
    modal = Modal.new(params)
    if modal.save
      p 'came here ************'
      p 'came here ************'
      #  Do some operations here
      return true
    else
      return false
    else
  end
end

【讨论】:

  • 这样调用:CreateModalService.create(data: data)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
相关资源
最近更新 更多