是否可以保留传递给延迟作业的模型中的跟踪更改?
Is it possible to preserve tracked changes in model passed to a delayed job?
我希望在我的模型更改时执行一些昂贵的操作,所以我在延迟作业中异步执行。在这项工作中,我需要能够准确地说出变化是什么,所以我将更改后的模型作为参数传递给延迟的工作。
现在,延迟作业似乎在作业开始时从数据库中获取模型的新(原始)版本 运行,它没有我需要的跟踪更改。
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
散列,而不是模型本身,但这会使延迟的作业代码更加复杂,因为它无论如何都需要使用模型实例(所以我需要获取它并将模型和更改用作单独的对象)。
有没有什么方法可以将模型传递给延迟的作业,同时保留跟踪的更改?
永远不要将模型对象发送给工作人员,只需发送 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
我希望在我的模型更改时执行一些昂贵的操作,所以我在延迟作业中异步执行。在这项工作中,我需要能够准确地说出变化是什么,所以我将更改后的模型作为参数传递给延迟的工作。
现在,延迟作业似乎在作业开始时从数据库中获取模型的新(原始)版本 运行,它没有我需要的跟踪更改。
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
散列,而不是模型本身,但这会使延迟的作业代码更加复杂,因为它无论如何都需要使用模型实例(所以我需要获取它并将模型和更改用作单独的对象)。
有没有什么方法可以将模型传递给延迟的作业,同时保留跟踪的更改?
永远不要将模型对象发送给工作人员,只需发送 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