Mio
Mio

Reputation: 1502

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":"[email protected]",
         "groups":[
            {
               "id":5282,
               "name":"test"
            },
            {
               "id":8880,
               "name":"everybody"
            }
         ]
      },
      {
         "id":119507,
         "first_name":"eriglk",
         "last_name":"wife",
         "email":"[email protected]",
         "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'

Upvotes: 0

Views: 1432

Answers (2)

jtf
jtf

Reputation: 125

I ran into the same issue, and figured out a fix given Gennady & Beni's responses, but it still took some time for me to get up and running.

see http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html

I created app/serializers/user.js:

import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    isNewSerializerAPI: true,
    attrs: {
        groups: { embedded: 'always' },
    }
});

and in app/model/user.js

export default DS.Model.extend({
     groups: DS.hasMany('group', {async: false}),
});

And then the model loaded the embedded properties right up!

Upvotes: 1

Gennady Dogaev
Gennady Dogaev

Reputation: 5991

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.

Upvotes: 2

Related Questions