Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember-data: how to share and update a object in transaction between controller actions?

I've found on GitHub a good working example for ember-data under https://github.com/dgeb/ember_data_example and try to extend it by nested resource ('has_many: comments'). In the original example a new transaction is created every time the edit view is on and it is submitted/rolled back if the edit mode is leaved.

I wand to add a new comment into content.comments I can't do it and have the error because the 'content' is already in transaction (Error: assertion failed: Once a record has changed, you cannot move it into a different transaction).

Is the idea I try to realize wrong and I must take another way?

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;
  }
});
like image 772
plapinhh Avatar asked Dec 19 '12 13:12

plapinhh


1 Answers

I think you could take inspiration from what I did: https://github.com/sly7-7/ember_data_example/commit/57ee7ea6ca44e3a2fbba96fff4ad088a8d786a3c

Perhaps simply doing this.get('content.comments').createRecord({body: ''}) will work. This call refers to the ManyArray.createRecord(), and use the transaction of the owner of the relationship to create the new record. see https://github.com/sly7-7/data/blob/master/packages/ember-data/lib/system/record_arrays/many_array.js#L163

like image 82
sly7_7 Avatar answered Oct 02 '22 07:10

sly7_7