Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I am using ActiveRecord::Relation delete_by method to delete a record but this is not triggering after_commit and after_destroy callbacks. See below example:

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? What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Is my expectation about the callbacks is right?

No. Your expectation to trigger a callback with delete_by is wrong.

What am I doing wrong?

Your understanding is not matching with doc.

As per the Doc, skipping-callbacks
delete_all will skip the 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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading