[英]How to display attributes of belongsTo object in Ember.js template
In my Ember app, a survey belongsTo a user; 在我的Ember应用程序中,调查属于用户; a user hasMany surveys.
用户有很多调查。 In my template, I would like to display a list of surveys, and the name of the user that created them.
在我的模板中,我想显示一个调查列表,以及创建调查的用户名。 For now, I am pushing side-loaded data into the store via the application route, and it is showing up in the ember inspector->Data.
现在,我正在通过应用程序路由将侧面加载的数据推送到存储中,并显示在ember inspector-> Data中。 The survey info is displaying correctly in the template, but the corresponding user's firstName will not appear.
调查信息在模板中正确显示,但是不会出现相应用户的名字。 Help/guidance appreciated.
帮助/指导表示赞赏。
survey.js (model) 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 (model) user.js (模型)
import DS from 'ember-data';
export default DS.Model.extend({
surveys: DS.hasMany('survey', {async: true}),
firstName: DS.attr()
});
application.js (application route) 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 (route) surveys.js (路线)
export default Ember.Route.extend({
model () {
return this.store.findAll('survey');
}
});
surveys.hbs (template) 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>
SOLUTION - updated application.js 解决方案 -更新了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
}
]
});
}
});
Payload relationship part is not correct. 有效负载关系部分不正确。 Should be:
应该:
relationships: {
user: {
data: {
id: 1,
type: 'user'
}
}
}
Also I think "user" payload should be in "included" section. 我也认为“用户”有效载荷应该在“包含”部分中。 JSONAPISerializer api
JSONAPISerializer API
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.