How can I do an Ember.js computed property on an Ember Data model based on an async relationship?

ember-data, ember.js

Solution

Your hasMany property is async, therefore it is a promise and its value must be accesible with the then method.

transaction.get('splits').then(function(splits) {

  split = store.createRecord('split', { amount: 250 }),
  splits.pushObject(split);

  split = store.createRecord('split', { amount: 1000 })
  splits.pushObject(split);

});

Problem

I have an Ember Data model and I'm trying to do a computed property based on properties of an async hasMany relationship. For some reason, it never seems to recompute. How can I do this properly? The code: ``` export default DS.Model.extend({ splits: DS.hasMany('split', { async: true }), amount: Ember.reduceComputed('splits.@each.amount', { initialValue: 0, addedItem: function(accValue, split) { return accValue + split.get('amount'); }, removedItem: function(accValue, split) { return accValue - split.get('amount'); } }) /* Neither of these work either. amount: Ember.computed.sum('splits.@each.amount') // This doesn't work amount: Ember.computed('splits.@each.amount', function() { return this.get('splits').reduce(function(pValue, split) { return pValue + split.get('amount'); }, 0); }) */ }); ``` The failing test (Expected `1350`, Got `0`): ``` import { test, moduleForModel } from 'ember-qunit'; import Transaction from 'my-app/models/transaction'; moduleForModel('transaction', 'Unit - Transaction Model', { needs: ['model:split'] }); test('amount', function() { var transaction = this.subject(); var store = this.store(); transaction.get('splits').addObjects([ store.createRecord('split', { amount: 250 }), store.createRecord('split', { amount: 1000 }) ]); equal(transaction.get('amount'), 1250); }); ```

Original source