I've got a situation where I need to 'do_this' after 'foo' has been created successfully and 'do_that' when 'do_this' has been executed without errors, like so:
class Foo < ActiveRecord::Base
around_create do |foo, block|
transaction do
block.call # invokes foo.save
do_this!
do_that!
end
end
protected
def do_this!
raise ActiveRecord::Rollback if something_fails
end
def do_that!
raise ActiveRecord::Rollback if something_else_fails
end
end
And the entire transaction should be rolled back in case one of them fails.
The problem however is, that 'foo' is always persisted even if 'do_this' or 'do_that' fails. What gives?
you don't need to do this, if you return false to a callback, it will trigger a rollback. The simplest way to code what you want is like this
after_save :do_this_and_that
def do_this_and_that
do_this && do_that
end
def do_this
# just return false here if something fails. this way,
# it will trigger a rollback since do_this && do_that
# will be evaluated to false and do_that will not be called
end
def do_that
# also return false here if something fails to trigger
# a rollback
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With