model:
DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
comments: DS.hasMany('comment', { async: true} ),
hasComments: Ember.computed.gt('comments.length', 0)
});
payload:
{
"id": "abcdefg",
"title": "some cats are cool",
"body": "",
"comments: ["100", "101", "102"]
}
But the hasComments
computed property triggers a fetch for each comment individually.. I don't want this :D
I know this works (avoids the fetch), but reaches into private API:
hasComments: Ember.computed.gt('data.comments.length', 0)
ember.js 1.8.1
ember-data 1.0.0-beta.11
Any other recommendations on achieving a computed property based off of the length
As of Ember Data 2.5 (mentioned in release notes) there is a feature called ds-references
which provides a way to check if if a hasMany relationship contains items or not without triggering a fetch for those items:
export default Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
comments: DS.hasMany('comment', { async: true} ),
hasComments: Ember.computed('comments', function() {
return this.hasMany('comments').ids().length > 0;
})
});
See this working in an Ember Twiddle
The ds-references feature implements the references API as described in RFC 57. References is a low level API to perform meta-operations on records, has-many relationships and belongs-to relationships:
- get the current local data synchronously without triggering a fetch or producing a promise
- notify the store that a fetch for a given record has begun, and provide a promise for its result
- similarly, notify a record that a fetch for a given relationship has begun, and provide a promise for its result
- retrieve server-provided metadata about a record or relationship
Source: Ember forum post and Ember Data 2.5 release blog post
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With