Save object and all relations

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?

1 Like

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  
})

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.

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
});
1 Like

Looking at the ember/data issues, this was just commited: https://github.com/emberjs/data/pull/1270

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;
});
2 Likes

Awesome. Thank you @ptsd.

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
  });
});

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

The solution to my error is here on SO.