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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33890458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:18:43  来源:igfitidea点击:

Difference between after_create, after_save and after_commit in rails callbacks

ruby-on-railsrubyactiverecordcallback

提问by Haseeb Ahmad

The difference between after_create, after_saveand after_commitin Rails is that:

Rails 中after_create,after_save和的区别在于after_commit

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

Is this the only difference among those, or are there any other major differences?

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

回答by Dusht

You almost got it right. However there is one major difference between after_commitand after_createor after_savei.e.

你几乎猜对了。但是,after_commitafter_create或之间有一个主要区别,after_save

In the case of after_create, this will always be before the call to save (or create) returns.

在 的情况下after_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). With after_commit, your code doesn't run until after the outermost transaction was committed. 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

Rails 将每次保存都包装在一个事务中,并且在该事务中运行 before/after create 回调(结果是,如果在 after_create 中引发异常,则保存将回滚)。使用after_commit,您的代码直到最外层事务提交后才会运行。这可能是创建的事务轨道或由您创建的轨道(例如,如果您想在单个事务中进行多项更改)。最初发布在这里

That also means, that if after_commitraises an exception, then the transaction won't be rolled back.

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

回答by Arvind singh

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‘s a create or update save)

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

after_commit-

after_commit-

Is called after the database transaction is completed.

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