【发布时间】:2015-09-23 10:02:39
【问题描述】:
在我的 Ember 应用中,调查属于用户;一个用户有很多调查。在我的模板中,我想显示一个调查列表,以及创建它们的用户的名称。现在,我正在通过应用程序路由将侧加载的数据推送到存储中,并且它显示在 ember 检查器->数据中。调查信息在模板中正确显示,但不会出现相应用户的名字。感谢您的帮助/指导。
survey.js(模型)
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user', {async: true}), //tried without async as well
title: DS.attr(),
post: DS.attr()
});
user.js(模型)
import DS from 'ember-data';
export default DS.Model.extend({
surveys: DS.hasMany('survey', {async: true}),
firstName: DS.attr()
});
application.js(应用程序路由)
export default Ember.Route.extend({
model() {
this.store.push({
data: [{
id: 1,
type: 'survey',
attributes: {
title: 'My First Survey',
post: 'This is my Survey!'
},
relationships: {
user: 1
}
}, {
id: 2,
type: 'survey',
attributes: {
title: 'My Second Survey',
post: 'This is survey 2!'
},
relationships: {
user: 1
}
}, {
id: 1,
type: 'user',
attributes: {
firstName: 'Tyler'
},
relationships: {
surveys: [1, 2]
}
}]
});
}
});
surveys.js(路线)
export default Ember.Route.extend({
model () {
return this.store.findAll('survey');
}
});
surveys.hbs(模板)
<ul>
{{#each model as |survey|}}
<li>
<strong>{{survey.title}}</strong> //This works
<br>
{{survey.post}} //This works
<br>
Author: {{survey.user.firstName}} //This does not work
</li>
{{/each}}
</ul>
解决方案 - 更新了 application.js
export default Ember.Route.extend({
model() {
this.store.push({
"data": [ //Added double quotes throughout to conform to documentation
{
"id": "1",
"type": "survey",
"attributes": {
"title": "My First Survey",
"post": "This is my Survey!"
},
"relationships": {
"user": {
"data": {
"id": "1",
"type": "user"
}
}
}
}, {
"id": "2",
"type": "survey",
"attributes": {
"title": "My Second Survey",
"post": "This is survey 2!"
},
"relationships": {
"user": {
"data": {
"id": "1",
"type": "user"
}
}
}
}
],
"included": [
{
"id": "1",
"type": "user",
"attributes": {
"firstName": "Tyler"
} //no need to include user's relationships here
}
]
});
}
});
【问题讨论】:
-
你能试试
{{log}}ing 或输出{{survey.user}}看看有什么吗?另外,我怀疑它是否有任何区别,但请尝试跨模型使用唯一 ID。顺便说一句,在这种情况下,异步不应该有任何区别。 -
唯一 ID 不走运。对异步也有同样的想法。 {{log survey.user}} 给出:类 {ember1442901526467: null, __nextSuper: undefined, __ember_meta: Object},看起来它是空的?
标签: ember.js ember-data relationships