0

In my rails app, I have a transaction block in a controller's create action in which I attempt to create two records.

def create
  ActiveRecord::Base.transaction do
    @foo = Foo.new(params[:foo].except(:bar))
    raise ActiveRecord::Rollback unless @foo.save
    @bar = Bar.new(params[:foo][:bar])
    raise ActiveRecord::Rollback unless @bar.save
  end
end

I'd like to be able to rescue from the Rollback so I can return an error indicating which save failed.

rescue ActiveRecord::Rollback => e
  @foo.errors = e if @foo.errors.blank?
ensure
  respond_with @foo
end

However, I never get into the rescue block. I assume this is because, as the rails documentation states, the transaction block eats the Rollback exception and doesn't re-raise it. Is there a way to force this exception to be re-raised?

glevine
  • 697
  • 1
  • 7
  • 19
  • Why not just raise your own exception? – deefour Dec 01 '12 at 05:42
  • I want to perform a rollback. Can I do that without the use of ActiveRecord::Rollback? – glevine Dec 01 '12 at 05:52
  • ok, updated my answer on your other question, so you do not have to rely on exceptions for normal program flow... – m_x Dec 01 '12 at 13:02
  • 1
    In case anyone stumbles upon this question. The answer @m_x is referring to is found at http://stackoverflow.com/questions/13621053. – glevine Dec 02 '12 at 05:20

0 Answers0