我希望在模型更改时执行一些昂贵的操作,因此我在延迟的工作中异步执行此操作。在这项工作中,我需要能够分辨出确切的变化,因此我将更改后的模型作为参数传递给延迟的工作。
现在,似乎延迟作业在作业开始运行时会从数据库中获取模型的新(原始)版本,该版本没有我需要的跟踪更改。
class MyModel < ActiveRecord::Base
after_save :perform_async_job
def perform_async_job
# Here, "self.changes" contains the changes
Delayed::Job.enqeue(AsyncJobPerformer.new(self), ...)
end
end
class AsyncJobPerformer
def initialize(model)
@model = model
end
def perform
# Here, "@model.changes" is empty
end
end
我当然可以只传递changes
哈希,而不传递模型本身,但是这会使延迟的作业代码变得更加复杂,因为它仍然需要使用模型实例(因此我将需要获取它,并将模型和更改都用作单独的对象。
在保留跟踪的更改的同时,有什么方法可以将模型传递给延迟的工作?
答案 0 :(得分:0)
从不将模型对象发送给工作人员,仅发送ID。您将需要传递更改哈希。工作者将无法保留由对象实例创建的更改。因此,是的,您需要将更改传递给您的工作人员。
class MyModel < ActiveRecord::Base
after_save :perform_async_job
def perform_async_job
# Here, "self.changes" contains the changes
Delayed::Job.enqeue(AsyncJobPerformer.new(self.class.name, self.id, self.changes), ...)
end
end
class AsyncJobPerformer
def initialize(model_name, model_id, params)
changes = params
@model = model_name.constantize.find(model_id)
#handle changes here with @model.update(changes) or a seperate method if need.
end
def perform
# Here, "@model.changes" is empty
end
end