{{Quest 1}}: Orphaned ember data model cleanup

2 min read • 1st June 2018
Orphaned ember data model cleanup image

Note
Level: Beginner

Supposing that you have an index route which displays a list of all records of book and another route that creates a record for the same, then the newly created record will also be displayed as an empty item. For example: https://ember-twiddle.com/5b3175b92732d04e6132040271d0b911?openFiles=templates.application.hbs%2C

EmberJS Cookbook is a valid book while there is an orphaned empty record displayed during listing!

Ember: Automatically destroy uncommited new model instance when navigating away from route

Note
Since you are creating a new model it remains as an orphan and you need to manually destroy it (roll it back). This can be done in the route's _resetController_ hook. Something like below:

import Route from '@ember/routing/route';
import { get } from '@ember/object';

export default Ember.Route.extend({
  model() {
    return get(this, 'store').createRecord('some-model');
  },

  resetController(controller, isExiting) {
    if (isExiting) {
      get(controller, 'model').rollbackAttributes();
    }
  }
});

Refer: https://emberjs.com/api/ember-data/3.1/classes/DS.Model/methods/rollbackAttributes?anchor=rollbackAttributes

Version: 1.12+

Enjoyed this article? Tweet it.

I guess you might be looking to add your comments? Glad to tell you that this section is under construction. But don't hold on to your thoughts! DM them to me on Twitter