0
votes

I am trying to define an Ember Data Model from the following response I am getting from the API. I am having issues defining the num_activity_per_map field since its an array of JSON objects however they do not have an id. If I use DS.hasMany('activityPerDate', {async:true}) complains it doesn't have a primary key.

{
"stats": {
    "num_users": 44,
    "num_activity_per_date": [
        {
            "date": "04-10-2015",
            "count": 6
        },
        {
            "date": "05-10-2015",
            "count": 8
        },
        {
            "date": "06-10-2015",
            "count": 7
        },
        {
            "date": "07-10-2015",
            "count": 5
        },
        {
            "date": "08-10-2015",
            "count": 3
        }
    ],
  }
}
1

1 Answers

0
votes

You have a few different options:

  1. Treat num_activity_per_date as a raw attribute by using DS.attr() to declare it.
  2. Treat num_activity_per_date as a custom attribute type by writing a custom transform.
  3. Treat num_activity_per_date as an embedded relationship.

It seems like you might want to go with #3. You'll want to override the serializer for the parent model to look something like this:

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        activityPerDate: { embedded: 'always' }
    }
});

Then declare activityPerDate: DS.hasMany('activityPerDate') and it should be taken care of. (I say should because I've never gotten embedded records to work properly. But it's also been a very long time since I've tried. YMMV.)