E.E.33
E.E.33

Reputation: 2011

What is the best way to undo a record update?

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?

Upvotes: 1

Views: 2526

Answers (2)

Tim Peters
Tim Peters

Reputation: 4144

Database transactions can be used in this case to undo changes.

YourModel.transaction do
  # update model here
  # api call here
  if api_was_successful
    # yay!
  else
    # probably do something here, like notify user
    raise ActiveRecord::Rollback
  end
end

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

Upvotes: 1

sajawikio
sajawikio

Reputation: 1514

You can do that. Whatever way you want to do it will work, nothing particular about it.

Also, if the remote update fails, maybe your remote copy still contains your old value that you still want? You can just use the remote copy to update your local copy, in that case, as well.

Upvotes: 1

Related Questions