RaresI
RaresI

Reputation: 461

How to remove a newly created model using Ember data?

I'm implementing a view for creating a new user.

App.UserNewRoute = Ember.Route.extend({
   model : function(params) {
        return this.store.createRecord('user');
   }
});

On the UserNewController there is a method which is triggered if the user presses cancel.

App.UserNewController = Ember.ObjectController.extend({
   //... code
   actions: {
       //.. other actions
       cancel: function(){
            var model = this.get('model');
            model.destroyRecord();
            this.transitionToRoute('users');
       }
   }
});

I'm always getting the following error:

Uncaught Error: Attempted to handle event `willCommit` on <App.User:ember751:null> while in state root.deleted.saved. 

I've tried using an alternative:

  model.deleteRecord();
  model.save(); 

I get the same error.

What am I doing wrong?

Upvotes: 0

Views: 122

Answers (2)

wenincode
wenincode

Reputation: 396

The issue might have to do with the fact that model.destroyRecord() returns a promise and that you are transitioning before that promise fulfilled. I have been using the following:

var model = this.get('model');
var _this = this;

// assuming you are working with a new model and not on say an edit page
// this will delete the new record and once the promise returns will transition routes
if (model.get('isNew')) {
  model.destroyRecord().then(function() {
    _this.transitionToRoute('route name');
  }
}

So that the transition only happens once the promise has been fulfilled. I am still an ember scrub but I figured it wouldn't hurt.

Upvotes: 1

RaresI
RaresI

Reputation: 461

According to this https://github.com/emberjs/data/issues/1669, the issue might be already fixed in newer Ember versions. I'm using Ember version 1.5.1 and Ember-Data version 1.0.0-beta.6

The workaround was to do a dirty check.

var model = this.get('model');
model.deleteRecord();
if (model.get('isDirty')) {
    model.save();
}
this.transitionToRoute('users');

Upvotes: 0

Related Questions