Sum nested hasMany


#1

For the life of me I cannot figure out how to sum nested data using asynch Ember models.

I have a model called Treatment which hasMany Fees. I created a computed property on the model which loads an array of the cost property, I then created an Ember.computed.sum on it. This works fine.

export default DS.Model.extend(ValidatableModel, {
  fees: DS.hasMany('fee', { async: true }),
  feeCosts: Ember.computed('fees.[].cost', function() {
    return DS.PromiseArray.create({
      promise: this.get('fees').then((fees) => {
        return fees.mapBy('cost');
      })
    })
  }),
  totalFees: Ember.computed.sum('feeCosts')
})

Now, I have another model which hasMany Treatments:

export default DS.Model.extend({
     treatments: DS.hasMany('treatment', {asynch: true}),
  treatmentFees: Ember.computed('treatments.[].totalFees', function() {
      return DS.PromiseArray.create({            
          promise: this.get('treatments').then((treatments) => {
              return treatments.mapBy('totalFees');
          })
      })
  }),
  totalTreatmentFees: Ember.computed.sum('treatmentFees')
})

When adding Treatments to Presentation, where the Treatment Fees have not yet loaded, {{treatment.totalFees}} displays the correct sum of that treatments fee costs ( meaning it loads it and then sums it and displays on screen the correct value ) However the {{presentation.totalTreatmentFees}} remains 0. If I add another treatment to the presentation the {{presentation.totalTreatmentFees}} will sum the first one added, but not add the second. This goes on for the next added, always leaving out the sum of the most recently added.

Once all treatments and fees are loaded everything works as expected. You can add and remove treatments from presentation and the {{presentation.totalTreatmentFees}} has no problem with the sum.

Why can’t Ember add? What am I doing wrong? I thought adding was like a core necessity for programming frameworks? Is this a bad assumption?