0

I am trying to serialize a user object and pass it to an ember client. My app uses the RESTserializer.

A user object has_one address object. There is no separate endpoint for just the address so I can't just provide a foreign key id and sideload it.

The JSON received just includes address as an object and looks something like this:

{"user": 
   {
    "id":"5",
    "name":"Andrew",
    "address": 
      { 
        "id":"3",
         "addressable_id":"5",
         "street":"1",
         "country_code":"US"
      }
   }

On the ember side I have a user model

App.User = DS.Model.extend({
  name: DS.attr('string'),

  address: DS.belongsTo('address'),

  //hasOne via belongsTo as suggested by another SO post:
  //http://stackoverflow.com/questions/14686253/how-to-have-hasone-relation-with-embedded-always-relation
});

and an address model

App.Address = DS.Model.extend({
  addressable_id: DS.attr('string'),
  street: DS.attr('string'),
  country_code: DS.attr('string'),

  user: DS.belongsTo('user')
});

Currently running this code throw an error in the console:

TypeError: Cannot read property 'typeKey' of undefined 

which can be fixed by removing the

address: DS.belongsTo('address'),

line in the user model but then the relationship doesn't load properly.

So what am I doing wrong configuring this? I am having a hell of a time finding up to date documentation on this.

Andrew
  • 942
  • 10
  • 26
  • Are you using the [embedded record mixin](http://stackoverflow.com/questions/24222457/ember-data-embedded-records-current-state/24224682#24224682)? – vhf Dec 23 '14 at 20:06
  • Actually looks like I may have misinterpreted the link you sent. That may fix my issue. – Andrew Dec 23 '14 at 20:14
  • That worked! If you resubmit that as an answer with some context I will accept it. Thank you so much! I had been wrestling with that for hours. – Andrew Dec 23 '14 at 20:33

1 Answers1

1

You need to use the DS.EmbeddedRecordsMixin on a per-type serializer.

In your case, you would need to do the following :

App.UserSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    address: {embedded: 'always'}
  }
});

as explained in this excellent answer.

Community
  • 1
  • 1
vhf
  • 61
  • 2
  • 8