使用RestSerializer返回多态有效负载

时间:2015-02-02 04:02:45

标签: javascript ember.js ember-data

说我有以下多态关系:

//animal.js
export default DS.Model.extend({});

//dog.js
import Animal from './animal';
export default Animal.extend({});

//cat.js
import Animal from './animal';
export default Animal.extend({});

//bird.js
import Animal from './animal';
export default Animal.extend({});

现在我想要取出所有的动物。

this.store.find('animal');

JSON响应应该来自默认的RestSerializer,我想将每个多态记录转换为各自的类?目前我的所有记录都转换为动物实例而不是正确的类型。

1 个答案:

答案 0 :(得分:2)

当关系是多态的时,服务器响应应指示ID和返回对象的类型(RESTSerializer默认执行此操作); e.g:

{
  "animals": [
      {
      // ... other attributes
      "type": "dog" // attribute that tells ember data what kind of Animal to instantiate
      },
      {
      // ... other attributes 
      "type": "cat" // attribute that tells ember data what kind of Animal to instantiate
      },
      {
      // ... other attributes
      "type": "bird" // attribute that tells ember data what kind of Animal to instantiate
      },
  ]
}

这意味着加载数据时,ember-data应根据数据中包含的“类型”实例化正确的Animal对象。 (假设Animal模型使用属性polymorphic: true)声明

以下是一些有用的示例:


修改

您需要配置模型以使其具有多态性。在您的情况下,您可以添加包含许多Zoo个对象的Animal父对象:

//zoo.js
export default DS.Model.extend({
    animals: DS.hasMany('animal', { polymorphic: true });
});

//animal.js
export default DS.Model.extend({
   zoo: DS.belongsTo('zoo');
});

//dog.js
import Animal from './animal';
export default Animal.extend({
    // attributes ...
});

//cat.js
import Animal from './animal';
export default Animal.extend({
    // attributes ...
});

//bird.js
import Animal from './animal';
export default Animal.extend({
    // attributes ...
});

现在,您可以向JSON添加Zoo模型,其中包含Animal个对象的多态数组的ID:

"zoos": [{
        "id": 1,
        "animals": [123, 456, 789], // animal ids
    }],
"animals": [{
        "id": 123,
        "type": "dog" // attribute that tells ember data what kind of Animal to instantiate
        // ... other attributes
    },{
        "id": 456,
        "type": "cat" // attribute that tells ember data what kind of Animal to instantiate
        // ... other attributes 
    },{
        "id": 789,
        "type": "bird" // attribute that tells ember data what kind of Animal to instantiate
        // ... other attributes 
    }]

你会像store.find('zoo', 1)那样请求这个JSON。

这是一款非常实用的应用,可帮助您了解如何根据模型构建JSON响应。 ---> LINK

Another useful example for ember-data polymorphism