I am using the ActiveModelAdapter to store models in our Rails backend. When the save fails, I’d like to remove it from the store. I tried verious different variantes, but none worked so far.
You need to call unloadRecord() after calling rollback(). It is a two step process in that you can’t unload dirty records from the store nor can you unload records that are in the process of being deleted (otherwise known as being ‘inflight’).
Looks like you got back a 422 response, which right now leaves the record in an ‘inFlight’ state (see https://github.com/emberjs/data/issues/1632 and https://github.com/emberjs/data/issues/1764). My workaround when getting a 422 response was to call record.transitionTo(‘created.uncommitted’). From there you should be able to delete the record. I’m guessing this will change in a future release of Ember Data since there’s been some discussion around it.
Thanks, that worked. It only works for 422 status codes, though. For 400, no workaround is necessary and applying the transitionTo('created.uncommitted') workaround raises another error. sigh
Any recommendations for a robust solution? For the time being, I’ll resort to just returning a 400 status from the backend…
hi @thiloginkel,
i ran into the same kind of frustration today. The following workarround works for me at the moment:
var model = this.get('model');
var store = model.store;
model.deleteRecord();
model.save().catch(function(err){
model.transitionTo('loaded.saved');
var payload = model.serialize({includeId: true});
store.unloadRecord(model)
store.pushPayload('nestedSet',{nested_set:payload});
});
I actually only needed to add the loaded.saved line:
record.destroyRecord().finally(() => {
// this bug should be fixed in future version of ember data (https://github.com/emberjs/data/issues/1632)
// fix from https://discuss.emberjs.com/t/deleting-model-from-store-after-save-failure/5072/8
record.transitionTo('loaded.saved');
record.unloadRecord();
});