Andrew
Andrew

Reputation: 1013

Ember data embedded has one relationship for ember-data.1.0.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.

Upvotes: 0

Views: 789

Answers (1)

vhf
vhf

Reputation: 61

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.

Upvotes: 1

Related Questions