Search code examples
ember.jsember-data

Refresh model from JSON


I have a deeply nested model with one-to-one and one-to-many relationships. Initially I retrieved this model from server using standard ember-data API.

What I need to do now is to update model (and all its relationships) from a plain JSON retrieved by an AJAX call.

I cannot use reload() method, because that would make an additional HTTP request - I already have the JSON payload, so no need for an extra HTTP request.

Is there a way to reload a model from JSON?


Solution

  • You can use pushPayload/push for to add new records and update the existing records in store.

    To revert all old changes, You can get all the records from store by peekAll, and iterate it for hasDirtyAttributes, if its true then unload it from store. after that you can use pushPayload to update the incomind records into store.

    let allRecords = this.get('store').peekAll('modelname')
    let dirtiedRecords = allRecords.filterBy('hasDirtyAttributes',true);
    dirtiedRecords.forEach((item) =>{
     item.unloadRecord();
    });
    //after that you can use pushPayload the result you got it from Ajax call.
    

    Refer:
    https://emberjs.com/api/data/classes/DS.Model.html#property_hasDirtyAttributes https://emberjs.com/api/classes/Ember.Enumerable.html#method_filterBy https://emberjs.com/api/data/classes/DS.Store.html#method_pushPayload