7

I have extended the program given in this stackoverflow answer to have a program that deletes all the records all at once. However, the deletion happens only in batches and does not delete everything all at once.

Here is a snippet of the function I am using in this JSBin.

deleteAllOrg: function(){
  this.get('store').findAll('org').then(function(record){
    record.forEach(function(rec) {
        console.log("Deleting ", rec.get('id'));
        rec.deleteRecord();
        rec.save();
    });
    record.save();
  });
}

Any idea how the program can be modified such that all records can be deleted at once?

I have also tried model.destroy() and model.invoke('deleteRecords') but they don't work.

Any help is greatly appreciated. Thanks for your help!

Community
  • 1
  • 1
user2431285
  • 661
  • 11
  • 19

1 Answers1

17

Calling deleteRecord() within forEach will break the loop. You can fix it by wrapping the delete code in an Ember.run.once function like this:

  this.get('store').findAll('org').then(function(record){
     record.content.forEach(function(rec) {
        Ember.run.once(this, function() {
           rec.deleteRecord();
           rec.save();
        });
     }, this);
  });

See this jsBin.

chopper
  • 6,649
  • 7
  • 36
  • 53
  • 7
    Nowadays you can call `this.get('store').findAll('org').invoke('destroyRecord')` to delete them all. – Jacob van Lingen Nov 03 '14 at 15:22
  • 2
    @Jacob, That actually doesn't work. Invoke uses the same forEach function. – NicholasJohn16 Mar 18 '15 at 06:44
  • 1
    @NicholasJohn16: You are right, you need to add `coalesceFindRequests: true` to the RESTAdapter to let it work. See: http://emberjs.com/blog/2014/08/18/ember-data-1-0-beta-9-released.html#toc_coalescing-find-requests – Jacob van Lingen Apr 08 '15 at 09:36
  • @JacobvanLingen `this.get('store').findAll('org').invoke('destroyRecord')` send a GET request to /orgs instead of DELETE – Anuj Kulkarni Jan 12 '16 at 21:16