Posted almost 5 years ago. Visible to the public. Repeats.

Cancelling the ActiveRecord callback chain

What Rails version Within before_* Within after_*
Cancel later callbacks Rails 1-4 return false return false
Cancel later callbacks Rails 5 throw :abort throw :abort
Rollback the transaction Rails 1-4 return false raise ActiveRecord::Rollback
Rollback the transaction Rails 5 throw :abort raise ActiveRecord::Rollback

Take care that your callbacks don't accidentally return false, since that cancels the chain in Rails 1-4. Since in Ruby the last expression of a method becomes its return value automatically, this can happen accidentally:

Copy
before_save :callback def callback call_to_method_that_happens_to_return_false end

If uncertain, return true explicitely:

Copy
before_save :callback def callback call_to_method_that_happens_to_return_false true end

When a callback raises an error

Exceptions raised in callbacks always rollback the transaction, but only exceptions that are not ActiveRecord::Rollback will bubble up to the caller.

Further reading

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Henning Koch
Last edit:
about 1 month ago
by Besprechungs-PC
Keywords:
before_validation, after_validation, before_save, after_save, before_update, after_update, before_create, after_create
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more