Save object and all relations


#1

Hello,

Let’s suppose the following example:

App.Developer = DS.Model.extend({
  languages: DS.hasMany('language')
});

App.Language = DS.Model.extend({
  developer: DS.belongsTo('developer')
});

I want to be able to save a developer instance, and to automatically save all the associated languages at the same time.
Is there any clean way to do this with the current status of ember-data, or do I have to loop through all the languages and manually save them after saving the developer?


#2

Maybe that is you look for:

developer.save().then(function(model){
    return  Ember.RSVP.all(model.get('languages').invoke('save'));
}).then(function(languages) {
  #transition the route  
})

#3

This could work. Unfortunately, invoke returns an array while I’d need a promise.
And I’d need to be able to transition the route, but only once all saves have been done.


#5

should work. untested.

var promises = new Array();
    
developer.save().then(function(developer) {
    developer.get('languages').forEach(function(language) {
        if(language.get('isDirty') {
            promises.push(language.save());    
        }
    });
}, function(error) {
   //developer failed to save;
});

Ember.RSVP.all(promises).then(function() {
    //transition here
}, function(error) {
    //one or more languages failed to save
});

#6

Looking at the ember/data issues, this was just commited:

developer.save().then(function(developer) {
    developer.get('languages').save().then(function() {
            //transition here
        }, function(error) {
            //a language failed to save
    });
}, function(error) {
   //developer failed to save;
});

#7

Awesome. Thank you @ptsd.


#8

This appears to not work in EmberJS 2.7. It throws an error on getting the children:

TypeError: newTrail.get(...).save is not a function

newObject.save().then(function (newTrail) {
  newTrail.get('assignments').save().then(function() {
    console.log('DONE'); <-- eventually a transition here
  });
});

#9

newTrail.get('assignments') returns an array, so I cannot call save on an array.

The solution to my error is here on SO.