2014-07-20 36 views
0

我有一个emberjs应用程序支持nodejs服务器和mongodb。目前我的数据库正在发送带有'_id'字段的文档。我有followign代码强制灰烬到治疗“_id”作为主键序列化ids当保存emberjs模型

App.ApplicationSerializer = DS.RESTSerializer.extend({ 
    primaryKey: '_id' 
}); 

在另一方面,我有一个“的hasMany”的关系有关这样两种型号:

App.Player = DS.Model.extend({ 
name: DS.attr('string'), 
thumbLink: DS.attr('string'), 
activeGame: DS.belongsTo('game', { async: true }), 
email: DS.attr('string'), 
firstName: DS.attr('string'), 
lastName: DS.attr('string'), 
admin: DS.attr('boolean') 
}); 

App.Game = DS.Model.extend({ 
    name: DS.attr('string'), 
    active: DS.attr('boolean'), 
    players: DS.hasMany('player', { async: true }) 
}); 

的问题是,当我尝试保存模型this.get('model').save())我的控制器上的ID是没有序列号,结果是余烬发送以下内容:

{"game":{"name":"Indie/Rock","active":false,"players":[],"_id":"53cbbf43daa978983ee0b101"}} 

正如你所看到的玩家阵列是,结果,服务器正在保存那个实际上是不正确的空数组。我知道可以在模型上使用{ embedded: true },并从服务器返回带有嵌入文档的模型,但我想保留异步功能。

我试图从EmbeddedRecordsMixing延长游戏串行如下所示:

App.GameSerializer = DS.ActiveModelSerializer 
        .extend(DS.EmbeddedRecordsMixin) 
        .extend({ 
        attrs: { 
         players: {serialize: 'ids', deserialize: 'ids'}, 
        } 
        }); 

但是,当我这样做,我从灰烬,即使ApplicationSerializer得到了以下错误suppossedly告诉灰烬用户_id作为主键:

Assertion Failed: Error: Assertion Failed: You must include an `id` for App.Game in a hash passed to `push` 

我的问题是,如果有可能维持异步余烬数据同时功能能够序列化该文档,其关系为ID,并使用_id作为主键。

谢谢。

+0

在http://stackoverflow.com/questions/24125334/ember-js-quiz-questions-save-delete-hasmany-data/24130793#24130793也提到 – Kingpin2k

回答

3

Ember数据在这方面很愚蠢,如果它是ManyToOne关系,它只包含belongsTo一侧的id。老实说,我已经在我的存档列表上提交了PR,但时间有限。

https://github.com/emberjs/data/commit/7f752ad15eb9b9454e3da3f4e0b8c487cdc70ff0#commitcomment-4923439

App.ApplicationSerializer = DS.RESTSerializer.extend({ 

serializeHasMany: function(record, json, relationship) { 
    var key = relationship.key; 
    var payloadKey = this.keyForRelationship ? this.keyForRelationship(key, "hasMany") : key; 
    var relationshipType = RelationshipChange.determineRelationshipType(record.constructor, relationship); 

    if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' 
     || relationshipType === 'manyToOne') { // This is the change 
     json[payloadKey] = get(record, key).mapBy('id'); 
     // TODO support for polymorphic manyToNone and manyToMany relationships 
    } 
    }, 
}); 
+0

我已经有了代码在我的应用程序,但它不能解决问题。如果我在serializeHasMany方法内做了一个console.log(记录)和console.log(json),那么玩家阵列是空的,尽管来自服务器/ api /游戏服务器上的服务器的数据已经填充了玩家阵列... – Rafls

+0

I说是代码在保存时删除数组。它只能从belongsTo端保存。 – Kingpin2k

+0

好吧,我误解了你,反正仍然没有解决办法,对吧? – Rafls