Resetting an ember-data model


#1

How do people deal with a model that has errored or is in the isError state.

I have hacked together a concoction like this:

I first of all trap the error:

contact.one 'becameInvalid', (result) =>
  @send 'flashError', contact
  result.reset()

contact.one 'becameError', (result) =>
  transaction.rollback()
  @send 'flashError', 'An error has occurred and the contact cannot be updated.'
  result.reset()

I then have a reset method on the model like this:

App.Model = DS.Model.extend
  reset: ->
    state = if @get('id')
              'loaded.updated.uncommitted'
            else
              'loaded.created.uncommited'

    @get('transaction').rollback()
    @get('stateManager').transitionTo(state)

How do others handle this?


#2

In the becameError or becameInvalid state, a commit will not work. The state must first be “reset” to uncommitted. In case of a new record, you can do this by using this.get('stateManager').transitionTo('loaded.created.uncommitted') - in case of an update use this.get('stateManager').transitionTo('loaded.updated.uncommitted'). Once in uncommitted state, you can try to commit again.

There is however one tricky problem: in case of the becameInvalid state, you will need to use the store defaultTransaction to do the subsequent commit. This results in some dirty checks in teh code; see my save code below:

save: function () {

//Commit - record goes in Flight state
this.transaction.commit();

//After a becameInvalid state, transaction.commit() does not work; use defaultTransaction in that case - very dirty check ...
if (this.get('stateManager.currentState.name') == "uncommitted") {
  this.get('store').get("defaultTransaction").commit();
}

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

author.one('didCreate', this, function () {
  this.transitionToRoute('author.edit', author);
});

//If response is error (e.g. REST API not accessible): becameError fires
author.one('becameError', this, function () {
  this.get('stateManager').transitionTo('loaded.created.uncommitted');
});

//If response is 422 (validation problem at server side): becameInvalid fires
author.one('becameInvalid', this, function () {
  this.set('errors', this.get('content.errors'));
  this.get('stateManager').transitionTo('loaded.created.uncommitted')
});

Hope this helps. Most probably, this is an area that will be improved in teh final release of Ember data.

Marc


#3

I am doing the exact same transition. I’m not sure I understand.