Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 727
yorbro Avatar asked Nov 10 '22 02:11

yorbro


1 Answers

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);
}
like image 133
Andrew Hacking Avatar answered Jan 04 '23 02:01

Andrew Hacking