I feel like I’m missing something obvious here, but here it goes.
I have local database that stores attributes of an Object. When I update an instance of the object, I also make a call to a remote API and update the record there as well. If that API call is unsuccessful, I want to roll back my local record to whatever was previously held. The only thing so far I can think to do is make a copy of the current record, before I update, and use that copy to re-update the record should my API call fail. Is there a best practice for doing this?
I feel like I’m missing something obvious here, but here it goes. I have
Share
Database transactions can be used in this case to undo changes.
Any exception in the transaction block causes database changes to be rolled back. The exception also gets re-raised, unless it is ActiveRecord::Rollback, so if your api call can raise exceptions you’ll still need to handle them (but at least your model changes will be rolled back. Only if the end of the block is reached will transaction be committed.
See: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html