Matthew Stopa
Matthew Stopa

Reputation: 3865

How do you create a non persisted model with EmberData?

I have an ember data app and I'm using createRecord to instantiate a model on a new records page. The problem is that this instantly creates the record in the store. So if someone navigates away from the the new record page the object is already persisted. There used to be a createModel method but it seems to have been removed. How is this handled now?

Upvotes: 0

Views: 113

Answers (2)

lawitschka
lawitschka

Reputation: 745

Alternatively, instead of checking for Model.isNew you can remove the record from the store once the user leaves the route using Route.resetController and Store.unloadRecord.

Route.resetController is meant for all controller clean up you have to do once the model changes or the user transitions away. IMHO this includes removing unsaved models from the store.

PostsNewRoute = Ember.Route.extend
  model: (params) ->
    @store.createRecord 'post'

  resetController: (controller, isExiting, transition) ->
    @store.unloadRecord controller.get('model') if isExiting

See http://emberjs.com/api/classes/Ember.Route.html#method_resetController and http://emberjs.com/api/data/classes/DS.Store.html#method_unloadRecord

Upvotes: 1

Daniel
Daniel

Reputation: 18680

You can check if Model.isNew so you can see has it been persisted. For example, you can do following in Handlebars to display list of records from database and hide new non-persisted models when you, for example, navigate backwards from model/add route:

{{#each item in model}}
  {{#unless item.isNew}}
    {{item.name}}
  {{/unless}}
{{/each}}

According to Ember API docs, DS.Store.createRecord method:

Creates a new record in the current store.

If you don't want to check if record isNew. You can have some properties for user input and call createRecord only if you are sure it can, and will, be persisted.

Upvotes: 1

Related Questions