在Rails 6应用中,我有以下代码。
class Reservation < ApplicationRecord
after_create :publish_creation
def publish_creation
Publishers::Reservations::CreateJob.perform_later(self)
end
end
class Publishers::Reservations::CreateJob < ApplicationJob
queue_as :default
def perform(reservation)
puts reservation.inspect #dummy code for testing
end
end
大多数情况下,我创建一个Reservation
(该记录始终在DB中创建,在下面出现错误
2020-02-14T09:54:03.707Z pid = 81787 tid = 1xmj警告:
ActiveJob::DeserializationError: Error while trying to deserialize arguments: Couldn't find Reservation with 'id'= 35651cf7-35bc-4da0-bb0d-6285ac093d22
Sidekiq第一次重试处理该作业时,它总是会找到Reservation
,并且一切正常。
Reservation id: "35651cf7-35bc-4da0-bb0d-6285ac093d22", analysis_id: "6b3b167b-1279-49c0-991a-b580c375fd0f", reservable_type: "User", reservable_id: "94f60c16-29d4-4372-983b-7544c393a7e6", reserved_between: 2020-02-10 08:00:00 UTC..2020-02-10 08:10:00 UTC, state: "scheduled", created_at: "2020-02-14 10:02:28", updated_at: "2020-02-14 10:02:28"
我在这里想念什么吗?这与我以development
模式运行时有关,并且一旦移至production
,它应该消失了吗?
您应使用after_commit
而不是after_create
。这是因为
after_create-在Model.save之后调用尚未保存的新对象(不存在任何记录)。在
after_create
的情况下,总是在保存(或创建)调用返回之前。 Rails将所有保存都包装在一个事务中,并且创建之前/之后的回调在该事务中运行。after_commit-在数据库事务完成之后被调用。使用
after_commit
,您的代码要等到最外面的事务提交后才能运行。