【发布时间】:2014-08-14 10:09:59
【问题描述】:
我面临需要将嵌入式关系持久保存到数据库中的情况。我在这个问题中描述了类似的情况。这是一个 ember-cli 项目。
我有两个模型:
//app/model/post.js
import DS from 'ember-data';
var Post = DS.Model.extend({
entry: DS.attr('string'),
comments: DS.hasMany('comment')
});
export default Post;
//app/models/comment.js
import DS from 'ember-data';
var Comment = DS.Model.extend({
text: DS.attr('string'),
post: DS.belongsTo('post')
});
export default Comment;
1 序列化器: //app/serializers/post.js 从“ember-data”导入 DS;
export default DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {
embedded: 'always'
}
}
});
1 条路线:
//app/routes/index.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.find('post', 1);
},
setupController: function(controller, model) {
var newComment = this.store.createRecord('comment', {});
newComment.set('text', 'xxxx comment');
model.get('comments').pushObject(newComment);
model.save().then(function(){
console.log(model.toJSON());
comments = model.get('comments');
comments.forEach(function(comment){
console.log("Comment: " + comment.get('text'));
console.log("Comment id: " + comment.get('id'));
});
});
}
});
所以,服务器返回的model钩子中的GET调用:
// GET /posts/1
{
"posts": {
"id": "1",
"entry": "This is first post",
"comments": [
{
"id": "1",
"post": "1",
"text": "This is the first comment on first post"
},
{
"id": "2",
"post": "1",
"text": "This is the second comment on first post"
}
]
}
}
当在 setupController 钩子中时,我在帖子中添加一条新评论并保存它,它实际上发送了一个带有以下正文的 PUT 请求:
// PUT /posts/1 -- Request
{
"posts": {
"id": "1",
"entry": "This is first post",
"comments": [
{
"id": "1",
"post": "1",
"text": "This is the first comment on first post"
},
{
"id": "2",
"post": "1",
"text": "This is the second comment on first post"
},
{
"post": "1",
"text": "xxxx comment"
}
]
}
}
服务器返回以下输出:
// PUT /posts/1 -- Response
{
"posts": {
"id": "1",
"entry": "This is first post",
"comments": [
{
"id": "1",
"post": "1",
"text": "This is the first comment on first post"
},
{
"id": "2",
"post": "1",
"text": "This is the second comment on first post"
},
{
"id": "3",
"post": "1",
"text": "xxxx comment"
}
]
}
}
但现在在控制台日志中我得到以下输出:
Comment: This is the first comment on first post
Comment id: 1
Comment: This is the second comment on first post
Comment id: 2
Comment: xxxx comment
Comment id: 3
Comment: xxxx comment
Comment id: null
为什么用id 返回的新评论被添加到帖子的 cmets 中而不是替换评论?
我做错了什么还是需要为此添加其他内容?
【问题讨论】:
标签: ember.js ember-data