Saving nested models


#1

I’m having an issue with saving nested models. I posted this question in StackOverflow, but didn’t get an answer as to how to fix it or why it isn’t working.

I have two models like this:

App.Build = DS.Model.extend({
	allegiance: DS.attr('number'),
	profession: DS.attr('number'),
            skills: DS.hasMany('skill')
});

App.Skill = DS.Model.extend({
    name: DS.attr('string'),
    value:DS.attr('number')
    });

In my app, I have controls to set the value of each skill. Then in the actions hash of my application controller, I have this function:

save:function(){
       var store = this.get('store');
       var skills = this.get('controllers.skills').get('model');
       var profession = this.get('profession');
       var allegiance = this.get('allegiance');
           
       var build = store.createRecord('build',{
           profession:profession,
           allegiance:allegiance
       });
            
       build.get('skills').pushObjects(skills);
            
       build.save();
  }

When I execute the save action, a post request is created with the following json:

{"build":{
    "allegiance":1,
     "profession":1,
          "skills":["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55"]}}

The list in skills being the ids for all the skills in my app.

My issue is that I need the value property submitted along with the build. How can I get ember-data to do that?

I’ve read a lot of threads on here and StackOverflow, but haven’t found a solution. In a few of them, it was suggested to add a belongsTo on the skill model, but in my experience, that just makes the skills completely drop from the json and seems really unnecessary in my app. I’ve tried overriding the serializer for both build and skill to no avail. I tried iterating over skills and adding just the id and value to the build model, but it gives me an error stating that only type skill can be put there. I’m not sure what to try next. :stuck_out_tongue:

Any assistance is appreciated. Thanks!


#2

It seems to me that you should indeed use a belongsTo relationship because that’s the best semantics for your use case. It’s a composition.

You should look into overriding BuildSerializer.