我在 GitHub 上找到了一个很好的工作示例,用于 https://github.com/dgeb/ember_data_example 下的 ember-data|并尝试通过嵌套资源('has_many:comments')扩展它。在原始示例中,每次打开编辑 View 时都会创建一个新事务,如果离开编辑模式,它将被提交/回滚。
我想在 content.comments 中添加一条新评论我不能这样做并且出现错误,因为“内容”已经在事务中(错误:断言失败:一旦记录发生更改,您就无法将其移动到不同的事务中)。
我试图意识到的想法是错误的,我必须采取另一种方式吗?
App.EditContactController = Em.Controller.extend({
content: null,
addComment: function () {
// ERROR here:
this.get('content.comments').addObject(App.Comment.createRecord({body: ''}));
},
enterEditing: function() {
this.transaction = this.get('store').transaction();
if (this.get('content.id')) {
this.transaction.add(this.get('content'));
} else {
this.set('content', this.transaction.createRecord(App.Contact, {}));
}
},
exitEditing: function() {
if (this.transaction) {
this.transaction.rollback();
this.transaction = null;
}
},
updateRecord: function() {
// commit and then clear the transaction (so exitEditing doesn't attempt a rollback)
this.transaction.commit();
this.transaction = null;
}
});
最佳答案
我想你可以从我所做的事情中获得灵感:https://github.com/sly7-7/ember_data_example/commit/57ee7ea6ca44e3a2fbba96fff4ad088a8d786a3c
也许只是做this.get('content.comments').createRecord({body: ''})
将工作。
该调用引用了 ManyArray.createRecord(),并使用关系所有者的事务来创建新记录。见 https://github.com/sly7-7/data/blob/master/packages/ember-data/lib/system/record_arrays/many_array.js#L163
关于transactions - Ember-data:如何在 Controller 操作之间的事务中共享和更新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13953019/