Jim
Jim

Reputation: 1062

How to update an existing record when creating a record with ember-data

When I try to create a model instance

record = this.store.createRecord('model', { /* whatever */ });
record.save();

And my API updates an already existing backend record instead of creating a new one. The API returns HTTP 200 [ok] (could also be 202 [accepted]) instead of 201 [created]. What is the ember way to have this record not created in the store if an instance of the same record is already there?

Right now if I "create" a record that turns out to update an existing record X times, I end up having the same record (with the same ID) repeated X times in my ember-data store.

Upvotes: 0

Views: 4349

Answers (1)

Martin
Martin

Reputation: 2300

When you use createRecord, you're telling Ember to add a new record to your store.

You need to fetch your record into your store first, if you want to update it:

this.store.find('model', id).then(function(record) {
  record.set('property', 'value');
  record.save();
});

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

Maybe you're looking for this.store.update( ... ), depending on your specific needs: http://emberjs.com/api/data/classes/DS.Store.html#method_update

Upvotes: 1

Related Questions