2
votes

I'm using the RESTAdaptor and Ember-Data 1.0.0-beta-2. I'm following the guidance in the Ember docs http://emberjs.com/guides/models/connecting-to-an-http-server/ about how the JSON returned from the server should be formatted for belongsTo relationships - but the related object is not being loaded. The Ember Inspector in Chrome is always showing the relationship as null.

The format of my JSON from the server is as follows:

{
"danceStyle": {
    "id": 2,
    "name": "Balboa",
    "partnered": true,
    "_links": {
        "parent": "/danceStyles/1"
    }
  }
}

And my Model definition is:

var attr = DS.attr;
var belongsTo = DS.belongsTo;
var hasMany = DS.hasMany;

App.DanceStyle = DS.Model.extend({
object: attr('string'),
name: attr('string'),
partnered: attr('boolean'),
parent: belongsTo('danceStyle', { inverse: 'children', async: true }),
children: hasMany('danceStyle', { inverse: 'parent', async: true })
});

The format of my JSON matches up to the format that the Ember docs say I should be using, so I'm banging my head against the wall trying to work out what's wrong! I've tried other ways of including the relationship within the JSON but with no results.

3

3 Answers

0
votes

I'm not sure that _links is used for relationships. (If so it is not well documented at all...)

Since you're using async:true you should be able to use JSON like this :

{
  "danceStyle": {
    "id": 2,
    "name": "Balboa",
    "partnered": true,
    "parent" : 1,
    "children" : [3,4]
  }
}

At that point, if you had loaded that model and then called .children() Ember Data would send a request like /danceStyles?ids[]=3,ids[]=4. Then your server should return :

{
  "danceStyles" : [
    {"id":3,...},
    {"id":4,...}
  ]
}

Alternatively, you can use "side loading" to deliver the children and parent along with the main model.

{
  "danceStyle": {
    "id": 2,
    "name": "Balboa",
    "partnered": true,
    "parent" : 1,
    "children" : [3,4]
  },
  "danceStyles" : [
    {"id":1,...},
    {"id":3,...},
    {"id":4,...}
  ]
}

I haven't actually dealt with side loading for self referential tree type models, but I know it works for an arrangement like Blog -> Post -> Comment.

0
votes

Did you try the following:

{
  "danceStyle": {
    "id": 2,
    "name": "Balboa",
    "partnered": true,
    "parent": 1
    "children": []  
  }
}
0
votes

As of today, you cannot use the "links" attribute for a belongsTo relationship. This can only be done with a hasMany relationship.

EDIT 9/23/14

"links" now works for both hasMany and belongsTo relationships. "links" away!