Rollback not triggering in rails transaction when catching errors

Viewed 634

I have some rails code in a controller action that has a transaction with a custom error.

When a speisfic error in a transaction happens I want to the transaction to rollback and render some json code, however I cannot seem to make the transaction rollback (it always commits) and then render some json. Here's my following code:

  def controller_action
    error_message = nil

    begin
      ActiveRecord::Base.transaction do
        code_that_moifys_db_to_rollback
        code_that_causes_custom_error
        some_more_code_i_dont_want_to_run
      end
    rescue SomeCustomError::Error
      error_message = 'this is an error message'
      raise ActiveRecord::Rollback
    end
  rescue ActiveRecord::Rollback
    # no rollback is getting triggered and data is now corrupt if json rendered
    render :json => {error: true, message: error_message}
    # however doing "raise 'xxxxx'" will cause a DB rollback in the transaction
  end

How do I both:

  • render json
  • and force the transaction to rollback

I think I may be misunderstanding how rollbacks are triggered, the strangest thing is if I raise in the second rescue it will trigger the transaction to rollback.

0 Answers
Related