Ember-data Serialize/Deserialize embedded records on 3rd level

萝らか妹 提交于 2019-12-13 05:15:28

问题


Pardon me for coming up with this title but I really don't know how to ask this so I'll just explain. Model: Group (has) User (has) Post Defined as:

// models/group.js
name: DS.attr('string'),

// models/user.js
name: DS.attr('string'),
group: DS.belongsTo('group')

// models/post.js
name: DS.attr('string'),
user: DS.belongsTo('user'),

When I request /posts, my server returns this embedded record:

{
  "posts": [
    {
      "id": 1,
      "name": "Whitey",
      "user": {
        "id": 1,
        "name": "User 1",
        "group": 2
      }
    }
  ]
}

Notice that the group didn't have the group record but an id instead.

With my serializers:

// serializers/user.js
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        group: {embedded: 'always'}
    }
});

// serializers/post.js
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        user: {embedded: 'always'}
    }
});

This expects that the User and Post model have embedded records in them. However, it entails a problem since in the json response doesn't have an embedded group record.

The question is, is there a way I can disable embedding records in the 3rd level?

Please help.


回答1:


Here is a good article about serialization:

http://www.toptal.com/emberjs/a-thorough-guide-to-ember-data#embeddedRecordsMixin

Ember docs:

http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html

Basically, what it says is that you have 2 options 1) serialize and 2) deserialize. Those two have 3 options:

  1. 'no' - don't include any data,
  2. 'id' or 'ids' - include id(s),
  3. 'records' - include data.

When you write {embedded: 'always'} this is shorthand for: {serialize: 'records', deserialize: 'records'}.

If you don't want the relationship sent at all write: {serialize: false}.

The Ember defaults for EmbeddedRecordsMixin are as follows:

BelongsTo: {serialize:'id', deserialize:'id'}

HasMany: {serialize:false, deserialize:'ids'}



来源:https://stackoverflow.com/questions/25727968/ember-data-serialize-deserialize-embedded-records-on-3rd-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!