I have ember models called survey
, question
and response
. survey
have multiple question
s, which have multiple response
s. Everyone response
has an attribute count
.
How to set the calculated value total_response_count
in the model survey
? In emberjs 1.0.0, they questions
are in DS.PromiseArray (due to async: true), so when I return the computed value, it appears in my template as an object, not a value.
I can easily access responses
from the model question
because it responses
is built in question
. However, Ember automatically creates promises for the questions
referenced survey
because {async: true}.
Poll Model:
App.Survey = DS.Model.extend({
title: DS.attr('string'),
owner_id: DS.belongsTo('user'),
questions: DS.hasMany('question', {async:true}),
total_responses: function() {
var question_cb = function(prevValue, item) {
return prevValue + item.get('total_responses');
};
return this.get('questions').then(function(questions){
return questions.reduce(question_cb, 0);
});
}.property('questions')
});
Question Model:
App.Question = DS.Model.extend({
survey: DS.belongsTo('survey'),
question: DS.attr('string'),
responses: DS.hasMany('response'),
total_responses: function() {
var response_cb = function(prevValue, item) {
return prevValue + item.get('count');
};
return this.get('responses').reduce(response_cb, 0);
}.property('responses')
});
Answer Model:
App.Response = DS.Model.extend({
response: DS.attr('string'),
count: DS.attr('number'),
question: DS.belongsTo('question')
});
I am using ember-1.0.0 and ember-data 1.0 beta-2.