加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:55:24 所属栏目:百科 来源:网络整理
导读:我使用 Ruby 2.0.0在Rails 4.2.0上运行.我遍历一个模型Production.all并调用production.finish!在.each循环中. 我的完成!方法,最后,用self.destroy删除自己.但是每个未定义的条目将在同一个循环中执行两次. def finish! self.progress = true self.save #
我使用 Ruby 2.0.0在Rails 4.2.0上运行.我遍历一个模型Production.all并调用production.finish!在.each循环中.
我的完成!方法,最后,用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,以便以后的crontabs无法访问此对象.我的调试日志表明同一个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’

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读