4
votes

I am struggling with a strange problem. I have a model called Activity with a property defined like this:

owner: DS.belongsTo('App.User', embedded: true)

The User is also a defined model when I'm getting the JSON response like this:

some single properties and

user: { id: etc. }

My all properties map well but the user embedded object from JSON doesn't map to the owner property. However, when I change

owner

to

user

It maps well. But I want to leave the owner because it's a better representation of what I mean. I tried this action:

owner: DS.belongsTo('App.User', key: 'user', embedded: true)

but it didn't help.

1
Could you explain what you mean when you say "it maps well" or "it doesn't map well"? Perhaps you could set up an example JSFiddle? - Rudi Angela
Did you ever figure this out? I'm having the same problem. - Brennan McEachran

1 Answers

1
votes

First, I recommend using the latest Ember / EmberData, but you will need to handle embedded records manually by enhancing extractSingle in a custom serializer (see example below). Also, you should define relationships like this:

App.Activity = DS.Model.extend({
  name:  DS.attr('string'),
  owner: DS.belongsTo('user')
});

App.User = DS.Model.extend({
  name:       DS.attr('string'),
  activities: DS.hasMany('activity')
});

Next, I recommend using the ActiveModelAdapter if you are using underscores when communicating with the server (i.e. like in EmberData 0.13):

App.ApplicationAdapter = DS.ActiveModelAdapter;

Finally, to use owner for a User, override typeForRoot in a custom serializer.

For example:

App.ApplicationSerializer = DS.ActiveModelSerializer.extend({
  typeForRoot: function(root) {
    if (root == 'owner' || root == 'owners') { root = 'user'; }
    return this._super(root);
  },

  // based on: https://github.com/emberjs/data/blob/master/TRANSITION.md#embedded-records
  extractSingle: function(store, type, payload, id, requestType) {
    var owner = payload.activity.owner,
        ownerId = owner.id;

    payload.owners = [owner];
    payload.activity.owner_id = ownerId;

    return this._super.apply(this, arguments);
  }
});

Example JSBin