How and when to fetch many-to-many relationship objects from the server


#1

I’m having some issue with my Ember web application. I’m using Ember 1.0 stable as the base JS framework and Ember-data.js 1.0 beta 1 to handle the relationships between model and the CRUD operations.

My simple application manages two entities: User and Order with a many to many relationship between them.

Here are the models:

 /*User Model*/
 App.User = DS.Model.extend({  
     first_name: DS.attr('string'),
     last_name: DS.attr('string'),  	
	fullName: function() {
  	return this.get('first_name') + ' ' + this.get('last_name');
	}.property('first_name', 'last_name'),	
     userorders: DS.hasMany('userorder', {async: true})
   });

 /*Order Model*/

 App.Order = DS.Model.extend({
	description: DS.attr('string'),
	userorders: DS.hasMany('userorder', {async: true})
 });

I created the model Userorder which maintains the one-to-one relationships with both User and Order.

Here is the model for Userorder:

  App.Userorder = DS.Model.extend({
     order: DS.belongsTo("order", {async: true, key: "order_id"}),
     user: DS.belongsTo("user", {async: true, key: "user_id"})
  });

My problem comes up when i try to get (into UserorderRoute) the single instance of a usersorder. Follows the code for UserorderRoute:

App.UserorderRoute = Ember.Route.extend({
  model: function(params) {
    return this.store.find("userorder", params.userorder_id);
  }
});

The userorder instance is correctly fetched, but if I try to access to the ‘order’ object I get undefined, (obviously, I get the same behavior with the access to ‘user’).


#2

Have you tried using the technique described in the docs for sideloading?

http://emberjs.com/guides/models/the-rest-adapter/#toc_sideloaded-relationships


#3

How did you resolve this?


#4

We (me and Frandre are working together on this project) followed that guide, the problem is that we navigate to that route after UserordersRoute (that fetches all the Userorder models from the server) so in UserorderRoute I think that the model is retrieved from the store and not from the server (I don’t see any GET request in the Chrome inspector).


#5

UPDATE: we have extended the DS.RESTSerializer with “extractSingle” function and now we are able to get the JSON as Ember-data requires. The result of this modification is that the HTTP GET request for the related object is done, but the template still doesn’t show any attribute.

Our guess is that the related model are instantiated but without attributes.

Anybody has the same issue?