Ember Data reloads associations when including a response in a PUT request

丶灬走出姿态 提交于 2019-12-10 14:55:14

问题


I have the following simple child-parent relationship.

App.Parent = DS.Model.extend({
  children: DS.hasMany('child')
});

App.Child = DS.Model.extend({
  parent: DS.belongsTo('parent')
});

I have a situation where I update an instance of a Child and persist the changes with a save(). This issues a PUT request. Usually, a PUT request returns a 204 No Content but I return a 200 OK with a JSON serialization of the model as the response, e.g.:

{
  child: {
    parent: 1
  }
}

Unfortunately, this causes a reload of the parent. So right after this, a GET request to /parents/1 is issued by Ember Data. How can I prevent this from happening?


回答1:


It sounds like you are returning partial results?

I haven't seen an appropriate solution on the interwebs that deals with partial updates in the right place. This may or may not fix your problem, but it could assist those who are having a similar issue because of partial results.

You could try overriding extractUpdateRecord in either your Application serializer, or on particular model serializers for those use cases where you return partial results.

Here is the default implementation:

/**
    `extractUpdateRecord` is a hook into the extract method used when
    a call is made to `DS.Store#update`. By default this method is alias
    for [extractSave](#method_extractSave).

    @method extractUpdateRecord
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {Object} payload
    @param {String or Number} id
    @param {String} requestType
    @return {Object} json The deserialized payload
  */
  extractUpdateRecord: function(store, type, payload, id, requestType) {
    return this.extractSave(store, type, payload, id, requestType);
  },

You will need to serialize the record to JSON and then merge in the payload data to update it. Something like the following:

extractUpdateRecord: function(store, type, payload, id, requestType) {
  var record = store.getById(type, id);
  var currentData = record.toJSON();
  var newData = this.extractSave(store, type, payload, id, requestType);
  return Ember.merge(currentData, newData);
}


来源:https://stackoverflow.com/questions/25486542/ember-data-reloads-associations-when-including-a-response-in-a-put-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!