In Rails 7, what is the right ActiveRecord callback to use if I need to prevent (or rollback) persistance on error?

35 views Asked by At

I'm moving from Rails 6.1 to Rails 7.0, and one of my tests is failing due to a record being persisted into the DB even after an error is raised in the transaction where the saving occurs. Something like this (in model):

def my_custom_save_method
  transaction do
    save!
    do_something_that_might_fail
  end
end

In Rails 6.1 the behavior was as expected: if nothing failed, the record was saved. If something failed, the transaction was aborted, and I got the error back in the controller.

After moving to Rails 7.0 the behavior changed: even if there's an exception in the method being called after the "save!", the model object is persisted into the db.

I've been through the guides for Rails 7 and there's not a lot of info on the callbacks, so I'm not even sure if this is the right approach; I'm trying to change the code so that it uses either an after_create or around_create callback ensuring that there is no persistence of the model object if the callback fails.

What is the right callback for this case?

I'm using after_create with a "raise ActiveRecord::Rollback" if anything goes wrong, and still the model object persists.

0

There are 0 answers