Read more

Cancelling the ActiveRecord callback chain

Henning Koch
December 05, 2013Software engineer at makandra GmbH
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 (returning nil is fine, though). Since in Ruby the last expression of a method becomes its return value automatically, this can happen accidentally:

before_save :callback

def callback
  call_to_method_that_happens_to_return_false
end
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

If uncertain, return true explicitely:

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

Henning Koch
December 05, 2013Software engineer at makandra GmbH
Posted by Henning Koch to makandra dev (2013-12-05 09:31)