我有一个Parent-Child-Grandchild关系,如下所示:
Course
- has_many Questions
Question
- has_many Answers
Answer
在我的问题模型上,我有一个计算属性answerCount
。当我到达问题路线/courses/1/questions
时,会计算计算属性,但不会在我在路线/courses/1
中进行评估。
我想向用户显示他们进入课程路线时未回答的问题的数量。但我只能在问题路线上做到这一点,因为这是异步has_many答案关系解决的时候。
如何在关系结算之前获取有关questions has_many answers
关系的信息?或者,如何强制关系在父路由/courses/1
中解决?
请告诉我我可以提供哪些其他信息。
编辑1
我使用过kingpin2k的建议,但仍未获得已解决的财产。以下是相关代码:
课程路线
model: function(params) {
return this.store.find('course', params.course_id);
},
afterModel: function(model, transition) {
// assuming questions are async
return model.get('questions').then(function(questions){
return Ember.RSVP.all(questions.getEach('answers'));
});
},
setupController: function(controller, model) {
controller.set('model', model)
},
课程控制器
unansweredQuestions: function() {
var self = this;
var questions = this.get("course.questions");
return questions.reduce(function(previousValue, question) {
if (question.get("answerCount") > 0) {
return previousValue;
} else {
return previousValue + 1;
};
}, 0)
}.property('course.questions.@each.answerCount'),
问题模型
answerCount: function() {
return this.get('answers').get('length')
}.property('answers.@each'),
使用此代码时,{{unansweredQuestions}}仍然会向我提供问题总数,直到我在问题/索引路线正确解析后才会出现问题。
答案 0 :(得分:2)
使用afterModel
。
您可以强制解决阻止路线完成的关系,直到关系解决为止。
model: function(){
// assuming we return the course here and you want to resolve questions and answers
},
afterModel: function(model, transition){
// assuming questions are async
return model.get('questions').then(function(questions){
return Ember.RSVP.all(questions.getEach('answers'));
});
}
答案 1 :(得分:0)
我的问题是我没有打电话从课程路线中的后端获得所有问题。
课程路线
在我的路线模型钩子中,我来自:
model: function(params) {
return this.store.find('course', params.course_id);
},
为:
model: function(params) {
return Ember.RSVP.hash({
course: this.store.find('course', params.course_id),
questions: this.store.find('question')
});
},
现在,当我在路线上时,我的问题和相关答案存在于我的商店中。感谢Kingpin2k让我朝着正确的方向前进。