Best practice for Ember data adding ids to embedded records?


#1

I have data from the server that looks like this:

var items = [
    { id: 1, details: [{a:1},{b:2},{c:3}] },
    { id: 2, details: [{x:1},{y:2}] }
];

and a data model

//models/item.js
export default DS.Model.extend({
 details: DS.hasMany('detail'), ...
});
//models/detail.js
export default DS.Model.extend({
 details: DS.belongsTo('item'), ...
});

The items have id’s but the details do not resulting in

Error while processing route: items.index Assertion Failed: You must include an id for app@model:detail: in an object passed to push

I solved this by adding ids in the serializer in a loop

import DS from ‘ember-data’;

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin,{
  attrs: {
    items: { serialize: 'ids', deserialize: 'records'}
  },
  extractArray: function(store, type, payload, id, requestType) {
     var idx = 1;
     payload.items.forEach(function(item) {
       item.details.forEach(function(detail) {
         detail.id  = idx++;
       })
     })
   return this._super.apply(this, arguments);
}
});

Is there a better way?