Random thoughts about the world of programming

Using Transactions in Ember Data - Part 1

Feb 2nd, 2013

We talked about transactions in one of the previous articles
(read it if you haven’t already), but we didn’t really touch on when to
use them in real world. One of the most common use cases for me is when
I just want to manage a single record while there are many changes
happening on the page.

Adding a record to a transaction is simple

12345678910

// say that we are in a controllerstore=this.get("store");// this ALWAYS returns a new transactiontransaction=store.transaction();user=App.User.find(1);transaction.add(user);transaction.toString();// => "<DS.Transaction:ember955>"

Now this is obvious, but what if we need to commit the transaction in a
completely different action? Do we need to store the instance somewhere
to use it later?

The answer is NO, we can always return the transaction in which the
record is by calling .get("transaction"). We can even do it if we
decide to fetch the user again in a completely different part of the
application.

Personally I use this when I only care about one record, but I know that
there might be other which are dirty and I don’t want to commit those.
This happens almost every time you have two forms displayed at once.