简体   繁体   English

rails 回调中 after_create、after_save 和 after_commit 的区别

[英]Difference between after_create, after_save and after_commit in rails callbacks

The difference between after_create , after_save and after_commit in Rails is that: Rails 中after_createafter_saveafter_commit的区别在于:

  • after_save is invoked when an object is created and updated after_save在创建和更新对象时调用
  • after_commit is called on create, update and destroy. after_commit在创建、更新和销毁时被调用。
  • after_create is only called when creating an object after_create仅在创建对象时调用

Is this the only difference among those, or are there any other major differences?这是它们之间唯一的区别,还是还有其他主要区别?

You almost got it right.你几乎猜对了。 However there is one major difference between after_commit and after_create or after_save ie但是after_commitafter_createafter_save之间有一个主要区别,即

In the case of after_create , this will always be before the call to save (or create) returns.after_create的情况下,这将始终在调用 save(或 create)返回之前。

Rails wraps every save inside a transaction and the before/after create callbacks run inside that transaction (a consequence of this is that if an exception is raised in an after_create the save will be rolled back). Rails 将每次保存都包装在一个事务中,并且在该事务中运行 before/after create 回调(其结果是,如果在 after_create 中引发异常,则保存将回滚)。 With after_commit , your code doesn't run until after the outermost transaction was committed.使用after_commit ,您的代码直到最外层事务提交后才会运行。 This could be the transaction rails created or one created by you (for example if you wanted to make several changes inside a single transaction).这可能是创建的事务轨道或由您创建的轨道(例如,如果您想在单个事务中进行多项更改)。 Originally posted here最初发布在这里

That also means, that if after_commit raises an exception, then the transaction won't be rolled back.这也意味着,如果after_commit引发异常,则事务将不会回滚。

With Order of callbacks使用回调顺序

after_create - after_create -

Is called after Model.save on new objects that haven't been saved yet (no record exists)在 Model.save 之后对尚未保存的新对象调用(不存在记录)

after_save - after_save -

Is called after Model.save (regardless of whether it'sa create or update save)在 Model.save 之后调用(无论是创建还是更新保存)

after_commit - after_commit -

Is called after the database transaction is completed.在数据库事务完成后调用。

Also, after_commit will execute even if the record was only touched.此外,即使仅触及记录, after_commit 也会执行。 This may NOT be what you want.这可能不是您想要的。 after_save will not run after touch. after_save 将不会在触摸后运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM