我最擅长在最新版本的ember.js和使用RESTAdapter的ember-data中找到和/或拼凑一个hasMany / belongsTo关系的工作jsfiddle。到目前为止,我发现pre.4 baseline fiddle by @zgramana使新路由器进行了一些探索,@sly7-7 fiddle使用了必要的DS关系,但为了简洁起见绕过了路由器。
我可以在这里找到我摸索的WIP尝试将这些拼凑成一个有凝聚力的例子:http://jsfiddle.net/W2dE4/5/。我显然是ember.js的新手,这个小提琴充满了错误,所以请原谅缺乏技巧。
App.Store = DS.Store.extend({
revision: 11,
adapter: DS.RESTAdapter.create({})
});
App.Post = DS.Model.extend({
title: DS.attr('string'),
post: DS.attr('string'),
comments: DS.hasMany('App.Comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('App.Post'),
description: DS.attr('string')
});
store = App.__container__.lookup('store:');
store.load(App.Post, {
id: 1,
title: 'Post 1 Title',
post: 'Body of post 1',
comments:[1,2]
},
{
id: 2,
title: 'Post 2 Title',
post: 'text of post 2',
comments:[3,4]
},
{
id: 3,
title: 'Post 3 title',
post: 'text of post3',
comments:[5,6]
}
);
store.load(App.Comment, {id: 1, description: "Great post!"},
App.Comment, {id: 2, description: "Post sucks."},
App.Comment, {id: 3, description: "Nice style"},
App.Comment, {id: 4, description: "Horrible writing"},
App.Comment, {id: 5, description: "Ember.js FTW"},
App.Comment, {id: 6, description: "Get up get out n' get something"}
);
如果有人能指出我正确的方向来使这个小提琴工作,或链接到pre.4与RESTAdapter和hasMany关系的工作示例,我将永远感激你的慷慨。
谢天谢地!
答案 0 :(得分:4)
你的小提琴只有一些语法问题。我在这里用一个工作版本更新了它:http://jsfiddle.net/W2dE4/6/
1)您没有正确加载商店。要在同一个调用中加载多个项目,您需要使用loadMany,传入模型类和数组。
所以而不是:
store.load(App.Post, {
id: 1,
title: 'Post 1 Title',
post: 'Body of post 1',
comments:[1,2]
},
{
id: 2,
title: 'Post 2 Title',
post: 'text of post 2',
comments:[3,4]
},
{
id: 3,
title: 'Post 3 title',
post: 'text of post3',
comments:[5,6]
});
store.load(App.Comment, {id: 1, description: "Great post!"},
App.Comment, {id: 2, description: "Post sucks."},
App.Comment, {id: 3, description: "Nice style"},
App.Comment, {id: 4, description: "Horrible writing"},
App.Comment, {id: 5, description: "Ember.js FTW"},
App.Comment, {id: 6, description: "Get up get out n' get something"}
);
应该是:
store.loadMany(App.Post, [
{ id: 1, title: 'Post 1 Title', post: 'Body of post 1', comments: [1,2] },
{ id: 2, title: 'Post 2 Title', post: 'text of post 2', comments: [3,4] },
{ id: 3, title: 'Post 3 title', post: 'text of post 3', comments: [5,6] }
]);
store.loadMany(App.Comment, [
{ id: 1, description: "Great post!" },
{ id: 2, description: "Post sucks." },
{ id: 3, description: "Nice style" },
{ id: 4, description: "Horrible writing" },
{ id: 5, description: "Ember.js FTW" },
{ id: 6, description: "Get up get out n' get something" }
]);
2)您对#each的车把模板调用引用了错误的属性。
而不是:
{{#each comment in post.comments}}
{{comment.description}}
{{/each}}
应该是:
{{#each comment in content.comments}}
{{comment.description}}
{{/each}}
因为它是保存帖子数据的内容属性。
干杯!