transactions - Ember-data:如何在 Controller 操作之间的事务中共享和更新对象?

标签 transactions ember.js nested-attributes ember-data

我在 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/

相关文章:

c# - 单个事务中的多线程

postgresql - 带有可序列化隔离的 PostgreSQL 9.2.1 中的谓词锁定

javascript - 如何在 ember js 中重新加载整个集合?

javascript - 从不同的 Controller Ember.js 向模型添加新记录

php - MySQL 事务查询是否可以提高多个 SELECT 语句的性能?

c# - NHibernate - 只有选择,我应该提交还是回滚?

ember.js - 在 Ember.js 中创建新的 mixin 时,如何扩展多个 mixin

ruby-on-rails - 如何在Rails中使用json更新nested_attributes?

ruby-on-rails - rails4 collection select with has_many 通过关联和嵌套模型形式

ruby-on-rails - Rails 4:嵌套属性和 PG::NotNullViolation 错误