7

With Ember Data, I would like to know how to delete a record given that I know its id.

HaoQi Li
  • 11,970
  • 14
  • 58
  • 77

3 Answers3

10

Note that after calling rec.deleteRecord() you also need to call rec.save() to "commit" the deletion.

this.get('store').find('model', the_id_of_the_record).then(function(rec){
  rec.deleteRecord();
  rec.save();
});

You can see that this is necessary by adding a record in the JSBin above (http://jsbin.com/iwiruw/458/edit), deleting it, and then reloading the page. You'll see that the record is "resurrected" after the page reloads (or if you click the "Run with JS" button). Here's a jsbin with rec.save() added, where you can see that the records do not come back to life.

http://jsbin.com/iwiruw/460/edit

Jeremy Green
  • 8,547
  • 1
  • 29
  • 33
  • I have tried to extend this jsbin program so that we can delete all the records all at once. However, the deletion happens only in batches and does not delete everything all at once. Any idea how the program can be modified such that all records can be deleted at once? See [JSBin](http://jsbin.com/uYArAXa/1/) – user2431285 Oct 08 '13 at 18:51
  • For deleting all records at once, kindly refer to this [answer](http://stackoverflow.com/a/19260106/2431285) – user2431285 Oct 08 '13 at 23:58
9

In recent versions of Ember Data (beta 4 and newer), destroyRecord() was introduced, which does deleteRecord() and save() in one go, so a shorter way of doing what Jeremey Green proposed is:

this.get('store').find('model', the_id_of_the_record).then(function(rec){
  rec.destroyRecord();;
});
chopper
  • 6,649
  • 7
  • 36
  • 53
0

Please refer to Jeremy's answer where he adds the critical rec.save()

You can use:

this.get('store').find('model', the_id_of_the_record).then(function(rec){
    rec.deleteRecord();
  });

or

this.store.find('model', the_id_of_the_record).then(function(rec){
    rec.deleteRecord();
  });

See it in action in this jsbin.

Community
  • 1
  • 1
HaoQi Li
  • 11,970
  • 14
  • 58
  • 77