Transactionless Nested Ember Data Resources
This article references a pre-release version of Ember.js. Now that Ember.js has reached a 1.0 API this article is basically no longer relevant.
Working with Ember and Ember Data during its real-time development have been exciting and frustrating times. Ember offers a powerful convention-driven approach to building robust apps on the client-side and Ember Data aims to simplify the the way your app’s data is retreived and stored. Powerful things get boiled down to simple functions like
App.Post.find(). Currently though, Ember Data is still in alpha and undergoing frequent API breaking changes with an emphasis on breaking.
In an Ember app I’m currently working on, I had the need to nest things within a parent object. For example: a campaign has one address (street name, city, zip, etc) and an array of links (each with a title and url). On the Rails REST API, I only needed one endpoint since I don’t need to query campaigns by links or addresses, so I am just serializing them to the campaign model instead of creating separate models for them.
1 2 3 4 5
Ember Data by default though, wants to save each resource type at its own API end-point and only save the ID references of the related objects within the parent object. To get around this in a previous revision of Ember Data, I could simply add the
embedded option when defining a relationship and adding the
associations option into the object’s
toData function when sending the campaign back to the server.
1 2 3 4 5 6 7 8
A recent code refactoring revision undid this functionality though, so I was forced to find another solution. I tried muddling around building an extended REST API adapter and serializer but I could never seem to break free of deeply engrained conventions of state and transaction management where Ember Data always seemed to care about campaign links and locations as their own object entities. Every time
Store.commit() was called, a 404-ed POST request was sent to
/campaign_locations and I ended up with dirty transactions. Ew. All I wanted was for Ember Data to chill and not give these objects any special treatment as they are basically just array and object attributes of the Campaign. The workaround I created was to register transforms for attribute types called
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
In order to reap all the non-syncing benefits of
DS.Model with these nested objects and arrays, I have to save the model class name locally to each nested object (i.e.
type: "App.CampaignLink") before sending it to the server, so that when it is returned, I can instantiate it with
createRecord via the nifty
I’m sure there is room for improvement and perhaps this is an unideal solution, but it allows me to press forward with development and rely less on Ember Data’s changing conventions as a 1.0 release gets ironed out.