Search code examples
ember.jsember-dataember-cli

Ember.js embedded records don't work


I have a json like

{
   "meta":{
      "per":20,
      "page":1,
      "total":2
   },
   "users":[
      {
         "id":119506,
         "first_name":"erglk",
         "last_name":"wfe",
         "email":"bent@exemple.com",
         "groups":[
            {
               "id":5282,
               "name":"test"
            },
            {
               "id":8880,
               "name":"everybody"
            }
         ]
      },
      {
         "id":119507,
         "first_name":"eriglk",
         "last_name":"wife",
         "email":"benit@exemple.com",
         "groups":[
            {
               "id":5284,
               "name":"testf"
            },
            {
               "id":8880,
               "name":"everybody"
            }
         ]
      }
   ]
}

For the moment no problem to access the user but I have some difficulties to access the groups array. I've tried hasMany and belongsTo without success. I had errors. I've read few articles about EmbededRecordMixin but without any success.

If I declare in my models :

export default DS.Model.extend({
  first_name: DS.attr('string'),
  last_name: DS.attr('string'),
  email: DS.attr('string'),
  groups: DS.attr('group')
});

I get : Error while processing route: users Assertion Failed: Unable to find transform for 'group' Error: Assertion Failed: Unable to find transform for 'group'


Solution

  • We use DS.attr to tell Ember that this field is an attribute of a model, and optionally we can specify a type of this attribute. By default, only allowed types are string, number, boolean, and date. To support custom type, special class (transform) should be defined. That's what Embers is trying to tell you with this error message. How to define such class, you may find here

    But, you don't need to define a custom transform for your task. You need to define a relationship:

    export default DS.Model.extend({
      first_name: DS.attr('string'),
      last_name: DS.attr('string'),
      email: DS.attr('string'),
      groups: DS.hasMany('group', {async: false})
    });
    

    And use an EmbeddedRecordMixin, as described in official docs. I can assure you that it works as described there.