我在 Rails 4.2.0 和 Ruby 2.0.0 上运行。我遍历模型 Production.all
并在 .each 循环中调用 production.finish!
。
我的结局!方法最后使用 self.destroy 删除自身。但是每个未定义的条目将在同一个循环中执行两次。
def finish!
self.progress = true
self.save # that other crontabs can't access me anymore if the crontabs overlap
if DeliveredProduction.find_by_production_id(self.id)
# send me a notification, why this object still exists?
else
DeliveredProduction.create!(:production_id => self.id) # Each undefined times a get an Exception here because the production_id is already insert!
# ...
# do things here
end
self.destroy # my debug logs says that each entry was successful deleted
end
Rails 4.2.0 或 Ruby 2.2.0p0 有 Bug 吗?它只发生在 1-2 天后,一个被执行两次。该代码将由 crontab 执行。我还用 progress=true 更新了迭代中的所有 Production,这样以后的 crontab 就不能访问这个对象了。我的调试日志显示同一 Production 的第二次执行是在几秒后的同一时间(同一秒)。
最佳答案
你应该为这样的事情使用after_commit
回调:
after_commit :deliver!, on: :update, if: ->{|me| me.progress}
def finish!
self.update(progress: true)
end
def deliver!
DeliveredProduction.create!(:production_id => self.id)
self.destroy
end
Model#save
不保证在执行下一行代码时会保存记录。 after_commit
会。只知道 after_commit
的注意事项:
关于ruby-on-rails - 双重执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31456332/