deleteRecord does not remove record from hasMany

前端 未结 3 1416
夕颜
夕颜 2021-01-01 03:06

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

相关标签:
3条回答
  • 2021-01-01 03:21

    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.

    0 讨论(0)
  • 2021-01-01 03:22

    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.

    0 讨论(0)
  • 2021-01-01 03:24

    Here's a working JSBin demonstrating the general idea of deleting items : http://jsbin.com/ucanam/1059/edit

    Can you post an example of whatever is giving you problems?

    0 讨论(0)
提交回复
热议问题