Skip to content Skip to sidebar Skip to footer

How Do I Save Data To My Ember Store If The POST Response Contains Only An Id?

Ember data expects my server to return the full object after each successful POST. However, my API only returns a kind of meta-object that contains the id. When Ember receives this

Solution 1:

Looks like the existing data on the record is getting overwritten in the record's adapterDidCommit method.

See https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/model/model.js#L656-L657

One solution could be to extend that method to preserve existing data from the record. I believe it might look something like this.

DS.Model.reopen({
  adapterDidCommit: function() {
    var oldData = this.toJSON();
    this._super.apply(this, arguments); // calls the original adapterDidCommit method
    var newData = this._data;
    this._data = Ember.merge(oldData, newData);
  }
});

This code is probably not ideal because it modifies the DS.Model class but I didn't see a way to extend an adapter or serializer class to achieve a similar result.


Solution 2:

For what it's worth, I'm solving my problem at the moment with the following:

// Given a vanilla Javascript `data` object that contains your model data
var asset = App.Asset.store.createRecord('asset', data);
asset.save();

// The server response updated `asset` with an `id` but deleted everything
// else, so we copy the `id` to our `data` object and then update the store
data.id = asset.id;
App.Asset.store.update('asset', data);

This solution feels hacky and I'd much rather get it right the first time than do this little dance every time I need to save a record.


Post a Comment for "How Do I Save Data To My Ember Store If The POST Response Contains Only An Id?"