改造为BelongsTo

时间:2015-08-02 21:14:36

标签: ember.js ember-data

我想知道是否可以为belongsTo(以及通过扩展hasMany)创建转换,因为我的REST服务器返回如下定义的关系:

import DS from 'ember-data';

export default DS.Model.extend({
  lastname: DS.attr('string'),
  firstname: DS.attr('string'),
  company: DS.belongsTo('company'),
});

这样:

[
    {
        "firstname": "John",
        "lastname": "Doe",
        "company": {
            "uri": "<snip>/api/rest/company/5",
            "id": "5",
            "resource": "company"
        }
    }
]

虽然RESTAdapter的默认实现期望服务器响应如下:

[
    {
        "firstname": "John",
        "lastname": "Doe",
        "company": "5"
    }
]

1 个答案:

答案 0 :(得分:2)

使用Ember Data 1.13,假设您正在获取单个模型,则在应用程序序列化器中覆盖normalizeFindRecordResponse

// serializers/application.js
normalizeFindRecordResponse: function(store, primaryModelClass, payload) {

   var record = { id: payload.id, type: primaryModelClass.modelName };
   record.relationships = {};

   Object.keys(payload).forEach(function(key) {
     if (payload[key].id) { // it's an object with an id -> relationship
       record.relationships[key] = { data: { id: payload[key].id, type: key } };
     } else { // it's an attribute
       record.attributes[key] = payload[key];
     }
   })

   return { data: record };

}

这是Ember Data 2.0的前进方向:按摩传入的服务器数据以适应JSON API