Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleteRecord does not remove record from hasMany

When I call deleteRecord() on some of my hasMany relations, Ember Data sends a (successful) DELETE request, but the record is not removed from the view. I am displaying it using the render helper like this:

{{render "modules.list" modules}}

The interesting thing is that Ember Inspector reveals that after deleteRecord() the corresponding object is <App.Module:ember1182:null> and its parent is null, too. It's parent, however, still shows the record in its hasMany (as <App.Module:ember1182:null>) When I reload the page and then call deleteRecord(), it is removed from the view as expected.

It seems that deleteRecord() does not remove the record from the parent's hasMany array. Oddly enough this works fine in other parts of my code. One theory I have is that this has to do with the {render} helper, because wherever I use that I have the same issue, but I am not sure if that's what's causing the problem.

I am using the latest build of ember data (commit 2511cb1f77).

like image 739
chopper Avatar asked Sep 14 '13 21:09

chopper


2 Answers

I found the solution. It seems like deleteRecord calls clearRelationships, which in turn sets the belongsTo of the model to null. However it does not clear the inverse (i.e. it does not remove the model from the hasMany relation of the parent). The following code fixed it.

var model = this.get('model');
model.eachRelationship(function(name, relationship){
    if (relationship.kind === "belongsTo") {
        var inverse = relationship.parentType.inverseFor(name);
        var parent  = model.get(name);
        if (inverse && parent) parent.get(inverse.name).removeObject(model);
    }
});
this.get('model').deleteRecord();
this.get('model').save();

However in my opinion this should be handled by Ember (Data). It seems like it is (most of the time), since this worked fine in other parts of my code. So likely this situation is some sort of edge case. Any thoughts on what might be going on are much appreciated.

like image 70
chopper Avatar answered Oct 02 '22 06:10

chopper


It seems that setting the inverse parameter in the belongsTo relation fixes it without having to clean the relation manually in Ember Data 0.14.

App.Item = DS.Model.Extend({
  parent: belongsTo('parent', { inverse: 'items' }) 
});

So if you instantiate your child model through it's parent like the following :

App.ParentController = Ember.ObjectController.extend({
  actions: {
    add: function() {
      this.get('items').pushObject(this.store.createRecord('item'));
    }
  }
});

Any further call to the created Item deleteRecord instance method would remove it from its parent relation and remove it correctly from the view.

like image 24
Vala Avatar answered Oct 02 '22 07:10

Vala