Search code examples
ember.jsember-data

Correct way of deleting a model record with ember-data


I have a controller that lists all the units-of-measure in the system. When a user chooses a specific record in the Uom model I want to be able to delete it. I'm using Ember-Data beta-2. Here's what I have so far:

App.UomsController = Ember.ArrayController.extend({
    actions: {
        deleteRecord: function(id) {
            console.log("deleting: " + id);
            var promisedDelete = this.store.find('uom',id).then(function(uom){
                uom.deleteRecord();
            });
        }
    }
});

The action deleteRecord is called passing in a valid ID and a promise is returned. Using the then() functionality of the promise I then call Ember's deleteRecord() when the promise has been fulfilled and it appears to work locally. I say that because this record immediately disappears from the screen and the Ember Debugger. Unfortunately the delete has not been persisted to the backend and a reload of hte page immediately brings back the locally "deleted" record.

My questions are:

  1. Is this a reasonable way to execute a local delete?
  2. How do I persist a delete to the backend?

Solution

  • You will have to call uom.save() to persist the change to the backend after calling uom.deleteRecord().

    What you are doing could work, but seems a bit complicated (for example this.store.find('uom',id) will result into an unnecessary request to the backend). Try this:

    App.UomsItemController = Ember.ObjectController.extend({
        actions: {
            deleteRecord: function() {
                this.get('model').destroyRecord();
                // .destroyRecord() only exists in recent versions of ED
                // for previous versions use .deleteRecord() followed by .save()
                // (though you should really consider upgrading :))
            }
        }
    );
    
    App.UomsController = Ember.ArrayController.extend({
        itemController: 'uoms_item'
    });
    

    and in your template you will have something like this:

    {{#each content}}
        {{name}} <a href="#" {{action "deleteRecord" this}}>Delete</a>
    {{/each}}
    

    EDIT to answer comment below: If this.get('model') is returning a promise, the following should work.

            deleteRecord: function() {
                this.get('model').then(function(item) {
                    item.destroyRecord();
                })
            }