Ember.js 如何正确添加相关记录
我收集了一些评论和帖子Ember.js 如何正确添加相关记录,ember.js,ember-model,Ember.js,Ember Model,我收集了一些评论和帖子 App.Router.map(function () { this.resource("posts", { path: "/posts" }); this.resource("post", { path: "/:post_id" }, function () { this.resource("comments", { path: "/comments" }); }); }); App.Post = Ember
App.Router.map(function () {
this.resource("posts", {
path: "/posts"
});
this.resource("post", {
path: "/:post_id"
}, function () {
this.resource("comments", {
path: "/comments"
});
});
});
App.Post = Ember.Model.extend({
id: attr(),
name: attr(),
comments: Ember.hasMany("App.Comment", {
key: 'comments'
})
if embedded = comments: Ember.hasMany("App.Comment", {
key: 'comments',
embedded: true
})
});
App.Post.url = "/posts";
App.Comment = Ember.Model.extend({
id: attr(),
message: attr(),
post: Ember.belongsTo('App.Post', {
key: 'post'
})
});
我怎样才能:
comment\u id
添加到Post模型上的comment\u id:[]
中如果没有嵌入,我可以使用
post\u id
来输入评论,但是我很难将comment\u id
添加到帖子中。你必须将新的评论
推到post
上的comments
集合中
var post = this.get('post');
var comments = post.get('comments');
comments.pushObject(comment);
comment.save();
post.save();
这里有一个JSBin,它的基本思想是:使用create()
方法
// get a post instance to insert a new comment to.
var post = App.Post.create(); // or App.Post.find()
// insert a new comment.
var comment = post.get('comments').create();
comment.message = "Test Poster";
// since you are using embedded relationship,
// no need to save the comment, just save the post.
post.save();
如果您使用的是非嵌入式注释,请将您的关系更改为{embedded:false}
,只是不要忘记在注释上调用save
// if non-embedded
comment.save();
希望有帮助 如果这对任何人都有帮助的话——我在ember模型上加入了pull请求,修复了这个问题谢谢,我会尝试一下!我现在正在使用ember模型,所以我将改变一些情况,并让您知道结果如何。但这将强制执行第二个不必要的json请求。推送干净对象时,不应将父记录标记为脏记录