Search code examples
ember.jsember-datarelationship

EmberJS - How to remove an object from hasMany relationship and then repush it?


I try to remove a model from a relationship and later import it again by using pushPayload.

The relationship is only updated on one side but not an the reverse side.

this.get('store').pushPayload({
  folder: {
    id: 1,
    name: 'My folder'
  }
});

this.get('store').pushPayload({
  item: {
    id: 2,
    name: 'My item',
    parentFolder: 1
  }
});

var folder = this.get('store').peekRecord('folder', 1);
var item = this.get('store').peekRecord('item', 2);

console.log('Parent folder id: ', item.get('parentFolder.id'), 'Items length', folder.get('items.length'));
item.get('parentFolder').get('items').removeObject(item);
console.log('Parent folder id: ', item.get('parentFolder.id'), 'Items length', folder.get('items.length'));

this.get('store').pushPayload({
  item: {
    id: 2,
    name: 'My item',
    parentFolder: 1
  }
});
console.log('Parent folder id: ', item.get('parentFolder.id'), 'Items length', folder.get('items.length'));

I would expect to get the following output:

Parent folder id:  1 Items length 1
Parent folder id:  undefined Items length 0
Parent folder id:  1 Items length 1

But I get this one:

Parent folder id:  1 Items length 1
Parent folder id:  undefined Items length 0
Parent folder id:  1 Items length 0

The issue is the last Items length.

https://ember-twiddle.com/d58d95d5be0cc8750282b9cc48db6489


Solution

  • You need to unload the record if you are going to use pushPayload to add it back in and you wish the payload to "win" over what you have locally on relationships:

    item.get('parentFolder').get('items').removeObject(item);
    this.get('store').unloadRecord(item);
    this.get('store').pushPayload({
      item: {
        id: 2,
        name: 'My item',
        parentFolder: 1
      }
    });