Reputation: 59355
I have a tournament model with a collection of matches associated to it. Suppose I want to destroy all of the matches in the collection at once, how should that be done? Here is what I've tried:
var matches = tournament.get('matches').toArray();
for (var i = 0; i < matches.length; i++) {
matches[i].destroyRecord();
}
tournament.save().then(function(tournament) {
that.transitionTo('tournaments.setup', tournament);
});
This toArray
bit doesn't seem right, but it prevents modifying an iterable as I iterate through it. It seems that there should be a way to just destroy all of these matches at once, then save the tournament.
Upvotes: 2
Views: 1066
Reputation: 85
Here's a little 1 line trick to get that done
tournament.get('matches').invoke("destroyRecord"); // deletes all records in 1 shot
If you wish to use that as a promise
Ember.RSVP.all(tournament.get('matches').invoke("destroyRecord"))
.then(function(){
tournament.save()
.then(function(tournament) {
that.transitionTo('tournaments.setup', tournament);
});
});
Upvotes: 6
Reputation: 6366
Yes you don't want to iterate an array that you are removing items from so what you are doing with toArray()
is a valid approach. There is no destroyAll() or similar function to my knowledge.
Your question states that you want to destroy the matches, not just disassociate them from the tournament so that means destroying each match individually. The destroyRecord() function marks the record for deletion and then saves the change via the adapter.
Typically matches will be associated to the tournament via a foreign key so destroying each match should be enough to remove them from a tournament and not require saving the tournament separately unless there are other derived attributes on the tournament such as stats which you need to also save.
Upvotes: 3