1
votes

I've a problem deserializing an array with ember-cli and ember data. I've models such as:

Label=DS.Model.extend
   ..
   days:DS.hasMany('day')

Day = DS.Model.extend
    hours: DS.attr()

The received JSON is:

labels:[
  {
   id: 1
   days:[{
      hours: [1,10, 33, 44,55,21]
   }]
  }
]

Now: I can properly manage Embeddedrecord with EmbeddedREcordMixin but whenever an hours array is deserialized it is transformed into something like:

[0,0,0,0,1,0,0,0,1,0,0,0,0]

removing all original values.

I tryed defining a specific transform, or changing the relationship to async and normalizing the payload in a specific labelSerializerbut nothing seems to have effect and I wasn't able to identify where the array is actually modified..

Solution

Finally, it was a problem of the received data set. Some record, with the same id was overwriting others, creating that misleading result. With EmberData 1.0.0.beta8, no ArrayTransform is needed. Just plain DS.attr() did the job.

EDIT:

I've tried the same implementation on a non ember-cli application and it worked fine. I used EmbeddedRecordsMixin in the LabelSerializer to handle day embedded hasMany relation, as well as customized the normalizePayload and extractArray functions in order to fix small problems with ids etc.. But I'm quite new to Ember-cli, I'm not sure if I'm missing something. There is a need of special configurations in order to use ActiveModelAdapter, and the EmbeddedRecordsMixin?

EDIT2 Invalidate all about edit1...

EDIT3 After more testings, it is not a problem of Ember-cli. When I test the deserialization through store.pushPayload() any manipulations of the JSON done in the labelSerializer#normalizePaylod or labelSerializer#extractArry works as expected. Instead, when connecting to a remote server, the result array of values is a set of 0 and 1s.

1

1 Answers

1
votes

I had a similar problem with Ember-Cli and Ember Data. I solved it like this:

I created a file called array.js in the transforms folder of my Ember-cli project. (you can call the file what ever you like)

transforms/array.js

import DS from 'ember-data';

export default DS.Transform.extend({
  deserialize: function(serialized) {
    return serialized;
  },

  serialize: function(deserialized) {
    return deserialized;
  }
});

Then in my model, I did this:

somemodel.js

import DS from 'ember-data';

export default DS.Model.extend({
    listOfSomething: DS.attr('array') //same name as the transform-file you created
});

Check out the Ember CLI documentation Using modules and the resolver

Edit

After taking a close look at your example, I see that the JSON is not on the correct format that Ember expects. If you check out the Ember Documentation on relationship between models your JSON should look something like this:

labels:[
  {
   id: 1
   days:[1]
  }
]

days: [
    {
        id: 1,
        hours: [1, 10, 33, 44, 55, 21]
    }
]