Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using transactions within Rails around_create callbacks

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?

like image 307
velu Avatar asked Sep 06 '25 03:09

velu


1 Answers

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
like image 176
jvnill Avatar answered Sep 07 '25 21:09

jvnill