2

我有两个这样的模型:

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 模型中,然后保存。现在工作得更好了。现在生成的post数据是这样的:

{"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 和 value,这是我唯一需要的部分,但这给了我一个错误。之类的,不能用未定义的,必须是类型技能。

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

谢谢!!

4

2 回答 2

6

如果其他人有兴趣,我通过使用自定义 serliazer 覆盖 serlizer 来解决这个问题,Build如下所示:

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'
    }
});
于 2013-10-24T04:02:37.930 回答
0

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

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

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

此外,保存返回一个承诺,因此为了正确处理成功保存与失败,您可以像这样处理它。

 build.save().then(
    function(){
     console.log('Saved!');
    },
    function(){
     console.log('Failed to save');
    });
于 2013-10-18T20:34:47.287 回答