How to delete several hasMany relationships?


#1

Hi, I’m finding myself writing quite a lot of boilerplate when I need to remove several HasMany relationships.

Here’s a scenario: two models, user and playlist. Users can mark playlists as favorites. If a playlist is deleted, I need to remove that playlist object from every user, that has it in their favoritePlaylists: hasMany('playlist').

It currently looks like this and is quite a lot for something that I’m sure everybody needs. What am I missing? There must be an easier way :slight_smile:

var playlist = this.get('model');

// Delete the playlist from every user's 'favoritePlaylists' property
this.store.find('user').then(function(users) {
   users.forEach(function(user) {
      user.get('favoritePlaylists').then(function(favoritePlaylists) {
         favoritePlaylists.removeObject(playlist); // tries to remove even if it isn't there
         user.save().then(function() {
            Ember.debug('Playlist removed from user');
         });
      });
   });

   // delete the playlist itself
   playlist.destroyRecord();
   this.transitionToRoute('application');
});