Sean McCleary
Sean McCleary

Reputation: 3820

Marking ember-data records as existing

I have a somewhat unique circumstance where I wrote a caching layer for ember-data that serializes records to localstorage. When I deserialize my cache into the ember-data models I use this.store.createRecord('model_name', cacheData);. These records I am caching have existing values on the server. This works for me fine up until I want to save() the record. The save thinks the record is a new record even though it has an "id" attribute. When save() is called a POST is made to my application server instead of a PUT. Does anyone know a way to flag records in the store as not new.

Upvotes: 2

Views: 547

Answers (2)

IgorT
IgorT

Reputation: 348

You should use store.push to add already existing records instead of store.createRecord

http://emberjs.com/api/data/classes/DS.Store.html#method_push

Upvotes: 5

Peter Brown
Peter Brown

Reputation: 51697

I couldn't find anything official, but models do have an isNew property. Since this is a read-only property, you can't set it directly, but you can set it on the currentState object like so:

var model = this.store.createRecord('model_name', cacheData);
model.set('currentState.parentState.isNew', false);

model.get('isNew') // => false

I can't speak to whether this is the best way to do it, but it should do what you're asking. Make sure you have good tests :)

Upvotes: 1

Related Questions