Display inline Ember data object from JSON

I am struggling with a strange problem. I have a model called Activity with a property defined as follows:

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

User also a specific model when I get a JSON response as follows:

 some single properties and user: { id: etc. } 

All my properties display well, but the inline user object from JSON does not map to the property. However, when I change

 owner 

to

 user 

It displays well. But I want to leave the owner, because this is the best idea of โ€‹โ€‹what I mean. I tried this action:

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

but it did not help.

+4
source share
1 answer

First, I recommend using the latest version of Ember / EmberData, but you will have to process the built-in records to manually improve extractSingle in a custom serializer (see example below). In addition, you must define the following relationships:

 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') }); 

Further, I recommend using ActiveModelAdapter if you use underscores when communicating with the server (i.e., as in EmberData 0.13):

 App.ApplicationAdapter = DS.ActiveModelAdapter; 

Finally, to use owner for User , override typeForRoot in the user serializer.

For instance:

 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); } }); 

JSBin example

+1
source

All Articles