Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rollback a rails save/transaction?

In my controller I have some code like...

...
if user.save
    something = Something.where("thing = ?", thing)
    if !(something.nil?)
        render json: { something: something }
    else
        #I WOULD LIKE TO ROLLBACK THE user.save HERE
    end
else
    render json: { error: user.errors.full_messages }, status: :bad_request
end

I have tried

raise ActiveRecord::Rollback, "Could not create new User, Something was not found."
render json: { error: "Could not create new User, Something was not found"}, status: :unprocessable_entity

in place of the ROLLBACK COMMENT area above, but this does not work. The user.save ends up going through. It spits something out to 'rails s', but it does not rollback the last transaction.

like image 508
chris P Avatar asked Feb 21 '15 18:02

chris P


People also ask

How do Rails Transactions work?

Rails transactions are tied to one database connectionAnd as long as the transaction block is running this one database connection is open. So try to do as little as needed inside the transaction block, otherwise you will be blocking a database connection for more time than you should.

What is Active Record transaction?

Transactions in ActiveRecord We're calling the transaction method on the ActiveRecord::Base class and passing it a block. Every database operation that happens inside that block will be sent to the database as a transaction.


1 Answers

You need to wrap the code in a transaction for the rollback to work properly. Here's the documentation: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

Something like

ActiveRecord::Base.transaction do
  # the code from your question
end

The key is that both the user.save call (which modifies the DB) and the raise ActiveRecord::Rollback call need to be in that block.

like image 183
alexcavalli Avatar answered Sep 22 '22 15:09

alexcavalli