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?
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.
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.
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.
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.
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
You can run console in sandbox mode
$> rails c --sandbox
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With