【问题标题】:Difference between after_create, after_save and after_commit in rails callbacksrails 回调中 after_create、after_save 和 after_commit 的区别
【发布时间】:2015-11-24 09:56:40
【问题描述】:

Rails 中after_createafter_saveafter_commit 的区别在于:

  • after_save 在创建和更新对象时调用
  • after_commit 在创建、更新和销毁时被调用。
  • after_create 仅在创建对象时调用

这是它们之间的唯一区别,还是有其他主要区别?

【问题讨论】:

  • 该问题中的 after_commit 在哪里不重复?

标签: ruby-on-rails ruby activerecord callback


【解决方案1】:

你几乎猜对了。然而,after_commitafter_createafter_save 之间有一个主要区别,即

对于after_create,这将始终在保存(或创建)调用返回之前。

Rails 将每个保存都包装在事务中,并且创建前后的回调在该事务中运行(这样做的结果是,如果在 after_create 中引发异常,则保存将被回滚)。使用after_commit,您的代码在提交最外层事务之前不会运行。这可能是创建的事务轨道或您创建的一个(例如,如果您想在单个事务中进行多项更改)。原贴here

这也意味着,如果after_commit 引发异常,则不会回滚事务。

【讨论】:

  • 在 after_create 的情况下,这总是在调用 save(或 create)返回之前。我无法理解这种说法。谁能用其他词形容一下?
  • after_commit 将在createupdatedestroy 之后运行。但是,您可以使用on: 选项来指定您感兴趣的选项。after_commit :some_method, on: :create 甚至after_commit :some_method, on: [:create, :destroy] 或使用像after_commit(on: :update) do run_method() end 这样的块。
  • 在使用 ActiveStorage 时了解非常有用,谢谢。
  • 有一个简写 after_save_commit :some_method,因为 rails 6+ 相当于 after_commit :some_method, on: [:create, :destroy]
【解决方案2】:

按回调顺序

after_create -

在尚未保存的新对象上调用 Model.save(不存在记录)

after_save -

在 Model.save 之后调用(不管是创建还是更新保存)

after_commit -

在数据库事务完成后调用。

【讨论】:

    【解决方案3】:

    此外,即使只触及记录,after_commit 也会执行。这可能不是你想要的。 after_save 不会在触摸后运行。

    【讨论】:

      猜你喜欢
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 2015-01-24
      相关资源
      最近更新 更多