在rails回调中after_create、after_save和after_commit之间的差异

时间:2021-06-17 01:20:14

The difference between after_create, after_save and after_commit in Rails is that:

Rails中的after_create、after_save和after_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 between them or are there other major differences?

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

1 个解决方案

#1


27  

You almost got it right. However there is one major difference between after_commit and after_create or after_save i.e.

你几乎说对了。然而,after_commit和after_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封装了事务内的所有保存,而在该事务中运行创建前后的回调(其结果是,如果在after_create中引发异常,则回滚保存)。使用after_commit,代码直到提交了最外层的事务之后才运行。这可以是由您创建的事务rails,也可以是由您创建的事务(例如,如果您希望在一个事务中进行多个更改)。最初发布在这里

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

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

#1


27  

You almost got it right. However there is one major difference between after_commit and after_create or after_save i.e.

你几乎说对了。然而,after_commit和after_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封装了事务内的所有保存,而在该事务中运行创建前后的回调(其结果是,如果在after_create中引发异常,则回滚保存)。使用after_commit,代码直到提交了最外层的事务之后才运行。这可以是由您创建的事务rails,也可以是由您创建的事务(例如,如果您希望在一个事务中进行多个更改)。最初发布在这里

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

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