简体   繁体   中英

serializing relationships ember-data

Okay so this is my json response:

item:

{
    "data": {
        "id": 1,
        "username": "rodzzlessa",
        "slug": "rodzzlessa"
     }
}

collection:

{
"data": [
    {
        "id": 34,
        "name": "HDG common nails 50lbs",
        "slug": "hdg-common-nails-50lbs4569",
        "description": "Accusantium ipsam impedit omnis sint dolorum.",
        "image_src": "nail-box-angle.png",
        "categories": {
            "data": [
                {
                     "id": 2,
                     "name": "nails",
                    "image_src": "nails-icon.png"
                }
             ]
         }
     }
  ]
}

I was able to make a serialzier for the main response:

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    extractArray: function(store, typeClass, payload) {
        payload.products = payload.data;
        delete payload.data;

        return this._super(store, typeClass, payload);
    }
});

Everything works great what I'm having an issue with is the relationships in this case a categories: DS.hasMany('category') . The error I get is:

A (subclass of DS.Model) record was pushed into the store with the value of categories being '{data: [object Object]}', but categories is a hasMany relationship so the value must be an array.

So my questions is which method should I edit to be able to serialize the relationship same way I did to its parent? I've added the DS.EmbeddedRecordsMixin to make my life a lot easier with relationships.

If I got it right, the error results from having and object inside of the categories key:

A (subclass of DS.Model) record was pushed into the store with the value of categories being '{data: [object Object]}', but categories is a hasMany relationship so the value must be an array.

Therefore you have to extract the array from this block categories: { "data": [...] } to categories: [...] .

You could simply iterate over the payload like this:

var idx, key, item;
var len = payload.data.length;
for (idx=0; idx<len; idx++) {
  item = payload.data[idx];
  for (key in item) {
    if (item[key].hasOwnProperty('data')) {
      item[key] = item.data;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM