I have a problem similar to this stack overflow question, except the answer doesn't seem to be working. I have a form in which the user creates a container module with a variable number of submodels. When the form is submitted, I have to save the container, the submodels, and make sure that the the hasMany relationship persists. My code (using Ember-Cli):
container:
var Container= DS.Model.extend({
name: DS.attr('string'),
submodels: DS.hasMany('submodel'),
lastModified: DS.attr('date')
});
export default Container;
submodel:
var Submodel= DS.Model.extend({
char: DS.belongsTo('container'),
name: DS.attr('string'),
desc: DS.attr('string'),
priority: DS.attr('number'),
effort: DS.attr('number'),
time: DS.attr('number')
});
export default Submodel;
ContainersNewRoute:
export default Ember.Route.extend({
model: function() {
return this.store.createRecord('container', {
...
});
}
});
ContainersNewController:
export default Ember.ObjectController.extend({
actions: {
addSubmodel: function() {
var submodels= this.get('model.submodels');
submodels.addObject(this.store.createRecord('submodel', {
...
}));
},
saveNewContainer: function () {
var container = this.get('model');
container.save().then(function(){
var promises = Ember.A();
container.get('submodels').forEach(function(item){
promises.push(item.save);
console.log(item);
});
Ember.RSVP.Promise.all(promises).then(function(resolvedPromises){
alert('all saved');
});
});
this.transitionToRoute(...);
}
}
});
The Ember Data itself works fine, transition to a view of the created container, with submodels listed. Refresh the page, and the submodels disappear from the container view.
I've tried a few variations, for example using pushObject rather than the addObject from the stack overflow answer. I've also tried using the Ember.RSVP callback to run container.save() a second time after the submodels have been saved.
After some further testing, I've found that the submodels are not persisting at all.
Is there a sane way to save 1) the container 2) the submodels 3) the hasMany/belongsTo relationships to each other?
Or does this some how need to be broken down into discrete steps where I save the container, save the submodels, the push the submodels to the container to get the hasMany relationship and resave the container, and lastly make the submodels belongTo the container and save the submodels again?