Reputation: 10939
I have a /posts/new
route for creating a new post
record. I am using the ember-form-for add-on, which provides helpers for creating forms. You are supposed to pass the form-for
component an object, and when you submit the form, form-for
calls the save()
method on the object. So it looks like you're supposed to pass it an instance of a model directly.
This means that I need to create a new post
model instance automatically when I navigate to this route. This is all good so long as I submit the form and create the new model instance. But what if I go to this route and then leave without submitting (i.e. saving) the new instance? It seems this will leave an unsaved model instance lying around in the store. Do I need to manually destroy this instance if I navigate away from the route, or is there some more elegant way to do this? If I do need to manually destroy it, what's the appropriate hook? deactivate
is a route method but my new instance is stored on the controller.
NOTE: I've seen this existing answer, but it's from 2013. Wondering if there's something cleaner available now.
Upvotes: 2
Views: 355
Reputation: 803
Since you are creating a new model, you need to manually destroy it (roll it back). This can be done in the route's resetController
hook. Something like below:
// Your route.js file
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();
}
}
});
Upvotes: 4