ActiveRecord after_rollback callback not triggered

Viewed 419

Since upgrading to Rails 6, I'm unable to get the after_rollback callback to fire. I've verified this doesn't work on Rails 6.0.3.6 or 6.1.3.1. Any help is appreciated!

class User < ActiveRecord::Base

  after_rollback do |user|
    puts "You have rolled back!"
  end

  validates_presence_of :name
end


> User.first.update!(name: nil)
ActiveRecord::RecordInvalid (Validation failed: Name cant be blank)

> User.create!
ActiveRecord::RecordInvalid (Validation failed: Name cant be blank)

According to the documentation the after_rollback should be triggered after a create, update, or destroy are rolled back

1 Answers

The default DB transactions are only opened after successful validation of the entity to be saved unless you manually open them. Try

User.transaction do
  User.first.update!(name: nil)
end
Related