/ Ember Data

References API in Ember 2.4

Update It looks like the references API is actually not enabled on 2.4.0-beta.1 branch. It will be set up for 2.5 if feedback is good.

In the Ember 2.4.0 beta that was released last week we saw the addition of a new API for reasoning about the relationships on your Ember Data models.

Interacting with a hasMany or belongsTo relationship is different to interacting with regular fields, in that you're working with a Promise instead of the actual content. E.g.

post.title // a string 'References API in Ember 2.4
post.comments // a Promise object for the comments

When using a relationship in a template you don't normally need to worry about this nuance because handlebars will handle the promise for you. In other cases, you may have to access the content of the promise explicitly (which is definitely taboo):

// don't try this at home kids
let comments = this.get('post.comments.content');

More importantly we have neither a mechanism to determine if the comments are loaded nor to inspect the ids of the comments without forcing them to load. For example

There are {{post.comments.length}} comments for this post

will cause the comments to be fetched, which might be earlier than you wanted.

Enter the references API

The new Ember data API gives you the opportunity to explicitly reason about a relationship directly and provides low level control over how the data is loaded:

post.hasMany('comments').ids() // the comment ids
post.hasMany('comments').reload(); // force the comments to reload

In the case where the server provides meta data about the response - for example when paginating comments - there's a method for that:


You can also access the content of a relationship without causing a call to the server to be made. This is useful for checking if the record has been loaded.

post.belongsTo('author').value() !== null

There are some other use cases here, for example notifying the store when a fetch has begun. For more information check out the release notes and RFC:

Open question

There are cases where we would want to display information about the relationship in a template, potentially as a computed property. How could we use or extend the interface to provide access in templates?

E.g. for accessing the meta property:

totalComments: Ember.computed.alias('comments.meta.total')

or as a helper

{{get (meta 'post.comments') 'total'}}
References API in Ember 2.4
Share this