after_commit 和 after_destroy 回调未在 ActiveRecord::Relation delete_by 方法上调用

after_commit and after_destroy callbacks are not called on ActiveRecord::Relation delete_by method

我正在使用 ActiveRecord::Relation delete_by 方法删除一条记录,但这不会触发 after_commitafter_destroy 回调。请参阅以下示例:

class User < ActiveRecord::Base
  after_commit :expire_cache
  after_destroy :expire_cache

  def expire_cache
    puts "expire_cache is called"
  end
end

User.delete_by(user_id: 1234) # doesn't trigger expire_cache method

我对回调的预期是否正确?我做错了什么?

Is my expectation about the callbacks is right?

没有。您期望用 delete_by 触发回调是错误的。

What am I doing wrong?

您的理解与文档不符。

根据文档,skipping-callbacks delete_all 将跳过 callbacks

  • delete_all Just as with validations, it is also possible to skip callbacks.
  • These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.

如果您希望回调 运行,请改用 destroy_by

User.destroy_by(id: 1234)

这些方法是在 Rails 6 中介绍的。更多信息在这里:

了解 deletedestroy 之间的差异也有助于: Difference between Destroy and Delete