delayed_job奇怪的例外

Tam*_*Tam 5 ruby-on-rails delayed-job

尝试使用delayed_job对作业进行排队,如下所示:

Delayed::Job.enqueue(BackgroundProcess.new(current_user, object))
Run Code Online (Sandbox Code Playgroud)

打印出来时,current_user和object不是nil.奇怪的是,有时刷新页面或再次运行命令有效!

这是异常跟踪:

  Delayed::Backend::ActiveRecord::Job Columns (44.8ms)   SHOW FIELDS FROM `delayed_jobs`

TypeError (wrong argument type nil (expected Data)):
  /Users/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/yaml.rb:391:in `emit'
  /Users/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/yaml.rb:391:in `quick_emit'
  /Users/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/yaml/rubytypes.rb:86:in `to_yaml'
  vendor/plugins/delayed_job/lib/delayed/backend/base.rb:65:in `payload_object='
  activerecord (2.3.9) lib/active_record/base.rb:2918:in `block in assign_attributes'
  activerecord (2.3.9) lib/active_record/base.rb:2914:in `each'
  activerecord (2.3.9) lib/active_record/base.rb:2914:in `assign_attributes'
  activerecord (2.3.9) lib/active_record/base.rb:2787:in `attributes='
  activerecord (2.3.9) lib/active_record/base.rb:2477:in `initialize'
  activerecord (2.3.9) lib/active_record/base.rb:725:in `new'
  activerecord (2.3.9) lib/active_record/base.rb:725:in `create'
  vendor/plugins/delayed_job/lib/delayed/backend/base.rb:21:in `enqueue'
Run Code Online (Sandbox Code Playgroud)

Dan*_*nne 7

我猜这是因为您将对象作为参数发送到您的作业(至少我假设current_user和对象实际上是对象而不是id).改为发送id,然后在开始执行时加载对象.

例如:

Delayed::Job.enqueue(BackgroundProcess.new(current_user.id, object.id))

class BackgroundProcess < Struct.new(:user_id, :object_id)
  def perform
    @current_user = User.find(user_id)
    @object = Object.find(object_id)

    ...
  end
end
Run Code Online (Sandbox Code Playgroud)

这样,将ActiveRecord序列化到数据库中就没有任何问题,并且在作业运行时总是会加载最新的更改.