ruby-on-rails - 双重执行代码

标签 ruby-on-rails ruby

我在 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 的注意事项:

Rails documentation on 'after_commit'

关于ruby-on-rails - 双重执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31456332/

相关文章:

ruby-on-rails - 脏(更改)属性 : since when are the values in the changeset strings (instead of objects)?

ruby-on-rails - 使用 PostGIS 和 Rails 查找边界框内的所有项目

ruby - 包含 'OR' 管道的正则表达式匹配输入字符串中的管道

ruby - 使用 Ruby 获取 AWS 区域名称

ruby - 检测哈希中是否存在键值对

html - 如何将 View 中的脚本移动到 Ruby On Rails 中的单独 js 文件?

ruby-on-rails - has_and_belongs_to_many 关系的自定义 Active Admin 表单输入

ruby-on-rails - 根据索引值映射对象

ruby mechanize 需要完整的类名

ruby-on-rails - 是否可以将 Vaadin 与 Rails 集成???如果是这样,怎么办?