保存嵌套模型

时间:2013-10-18 20:16:53

标签: ember.js ember-data

我有两个这样的模型:

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

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

在我的应用程序中,我有控件来设定每项技能的忠诚度,专业和价值(最高可达55)。

然后在我的应用程序控制器的动作哈希中,我有一个动作将构建模型保存到服务器。

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

      build.set('skills',skills);
      build.save();

      console.log('Saved!');
}

但是当构建模型发送到服务器时,技能属性是一个空数组:

{"build":{"allegiance":"1","profession":"1","skills":[]}}

我确定我做错了什么,但我无法弄清楚什么,也找不到任何关于它的好文档。另外一点,我关心提交的是技能ID和价值。

任何帮助将不胜感激!

更新:

根据Daniel的建议,我编辑了保存功能,使用pushObjects将技能放入Build模型,然后保存。它现在工作得更好。生成的帖子数据现在就像这样:

{"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"]}}

这是技能ID的列表。在帖子中没有提交任何其他属性。我已经尝试迭代技能,创建一个新对象,只是推入id和值,这是我需要的唯一部分,但这给了我一个错误。有点像,不能使用undefined,必须是类型技能。

这似乎是Ember数据应该本地处理的东西。是否有一些我缺少的东西让它在请求中发送其他技能属性?

谢谢!

2 个答案:

答案 0 :(得分:6)

如果有其他人感兴趣,我通过使用Build模型的自定义serliazer覆盖serlizer解决了这个问题:

App.BuildSerializer = DS.RESTSerializer.extend({
     serializeHasMany: function(record, json, relationship) {
         if(relationship.key === 'skills') {
            var skills = record.get('skills');
            var block = [];

            skills.forEach(function(skill, index) {
                var current = {};
                current.id = skill.get('id');
                current.value = skill.get('value')
                block[index] = current;
            });

            json['skills'] = block;

         } else {
             return this._super(record,json,relationship);
         }
     }
});

更新:

现在可以使用DS.EmbeddedRecordsMixin这样一种更简单的方法:

App.BuildSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin,{
    attrs: {
        skills: 'records'
    }
});

答案 1 :(得分:0)

技能模型是RecordArray吗?这是Ember数据使用的基础模型。您可以尝试创建记录,然后在事后使用pushObjects。

  var build = store.createRecord('build',{
      profession:1,
      allegiance:1
  });

  build.get('skills').pushObjects(skills);

另外,save会返回一个promise,所以为了正确处理成功保存而不是失败,你可以像这样处理它。

 build.save().then(
    function(){
     console.log('Saved!');
    },
    function(){
     console.log('Failed to save');
    });