Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rollback transaction after commit in rails

Can I rollback record after successfully saved?

Lets I have a user model with attribute name,email and so on.

For ex.

u=User.new
u.name="test_name"
u.email="[email protected]"
u.save

Now record will be successfully saved in database after that I want to rollback my transaction (not destroy or delete). Have any idea?

like image 989
RKP Avatar asked Feb 22 '13 10:02

RKP


People also ask

Can we rollback a transaction after it has committed?

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

How do I rollback an Active Record transaction?

ActiveRecord provides a particular error class that you can use inside a transaction to make a silent rollback. You roll back the transaction by raising the ActiveRecord::Rollback error, but the error isn't raised outside, as happens with other errors. Keep this behavior in mind and use it wisely.

What is the difference between commit and rollback?

The COMMIT statement lets a user save any changes or alterations on the current transaction. These changes then remain permanent. The ROLLBACK statement lets a user undo all the alterations and changes that occurred on the current transaction after the last COMMIT.

What does Active Record base transaction do?

Transactions in ActiveRecordEvery database operation that happens inside that block will be sent to the database as a transaction. If any kind of unhandled error happens inside the block, the transaction will be aborted, and no changes will be made to the DB.


2 Answers

You can do this with transactions, see http://markdaggett.com/blog/2011/12/01/transactions-in-rails/

Example:

User.transaction do
  User.create(:username => 'Nemu')
  raise ActiveRecord::Rollback
end
like image 188
ashtom Avatar answered Nov 03 '22 01:11

ashtom


You can run console in sandbox mode

$> rails c --sandbox
  • On exit all changes rollback to the point of enter.
like image 21
itsnikolay Avatar answered Nov 03 '22 01:11

itsnikolay