首先,我建议使用最新的 Ember / EmberData,但您需要通过增强extractSingle
自定义序列化程序来手动处理嵌入记录(参见下面的示例)。此外,您应该像这样定义关系:
App.Activity = DS.Model.extend({
name: DS.attr('string'),
owner: DS.belongsTo('user')
});
App.User = DS.Model.extend({
name: DS.attr('string'),
activities: DS.hasMany('activity')
});
接下来,ActiveModelAdapter
如果您在与服务器通信时使用下划线,我建议使用 (例如在 EmberData 0.13 中):
App.ApplicationAdapter = DS.ActiveModelAdapter;
最后,要在自定义序列化程序中owner
使用User
, 覆盖。typeForRoot
例如:
App.ApplicationSerializer = DS.ActiveModelSerializer.extend({
typeForRoot: function(root) {
if (root == 'owner' || root == 'owners') { root = 'user'; }
return this._super(root);
},
// based on: https://github.com/emberjs/data/blob/master/TRANSITION.md#embedded-records
extractSingle: function(store, type, payload, id, requestType) {
var owner = payload.activity.owner,
ownerId = owner.id;
payload.owners = [owner];
payload.activity.owner_id = ownerId;
return this._super.apply(this, arguments);
}
});
示例 JSBin