How to load two models in one JSON request in Ember-data?

Using Ember-data and Ember.js, I am trying to load two models with one JSON request. Models have a relation similar to this:

App.Person = DS.Model.extend({ name: DS.attr('string'), dogs: DS.hasMany('App.Dog'), }); App.Dog = DS.Model.extend({ name: DS.attr('string'), owner: DS.belongsTo('App.Person'), }); 

My server sends JSON as follows:

 { "dog": { "id": 1, "name": "Fido", "owner": { "id": 1, "name": "John Smith", "dogs": [1] } } } 

... And yet, the Ember data still sends a request (using findQuery) to my server, trying to get the JSON owner.

I have jsFiddle installed which demonstrates it here . To view the problem, you need to follow this link to activate the route / pattern:

http://fiddle.jshell.net/6kQ8s/2/show/#/dog/1

I did not define findQuery () in my adapter because I do not need to get the data that I have already sent ... Correct?

Does anyone know what I'm doing wrong here?

+4
source share
2 answers

I do the following (using revision 8 of ember-data data)

 App.Dog = DS.Model.extend({ name: DS.attr('string'), owner: DS.belongsTo('App.Person', { embedded: true }), }); 

Also, I have to tell the serializer to load the mapping for this relationship. Although not required, I use my own subclass of DS.Serializer. Upon initialization, the serializer loads a mapping for the Person class, which indicates that the inline relationship should be loaded.

  App.WOSerializer = DS.Serializer.extend({ init: function(){ this._super(); this.map(App.Dog, { person: { embedded: 'load' } }); }); 

Edit Question:

The serializer must be initialized in the adapter.

 App.adapter = DS.Adapter.create({ // ... serializer: App.WOSerializer.create() }); 
+2
source

Try using the embedded property.

 App.Dog = DS.Model.extend({ name: DS.attr('string'), owner: DS.belongsTo('App.Person', { embedded: true }), }); 
0
source

Source: https://habr.com/ru/post/1447901/


All Articles