4
votes

I had assumed that if a model in ember-data contained an id related to a second model, then the id could also be used to establish a belongsTo relationship to the second model object, as per the issue I created here on github. Apparently that is not the case.

Does anyone know the circumstance(s) required to have relationships between two objects that both exist in ember-data's store be related to each other? Do the related objects have to be loaded at the same time? (or come through on the same request in the case of the RESTAdapter) in order for the id references to work? In the event they don't come through on the same request, is there anyway to establish that relationship on later requests without have to add event handlers for the requests that look for relationships and set them manually? Here is an example of the issue I'm seeing:

App.ModelA = DS.Model.extend({
  name:      DS.attr('string'),
  modelBId:  DS.attr('number'),
  modelB:    DS.belongsTo('App.ModelB')
});

App.ModelB = DS.Model.extend({
  name: DS.attr('string')
});

App.ModelB.find(2);       // returns an object

modelA.get('modelBId');   // returns 2
modelA.get('modelB');     // returns null
2

2 Answers

2
votes

The ID of associated objects are useful when you want to load / save data, from a REST API for example. Then you can use the RESTAdapter and send the ID of the related objects.

For example, for a belongsTo relationship, ember-data assume that you will send a key model_b_id with the ID of the related object. Then ember-data will handle the loading of this object, typically by a call to the API : GET model_b/the_id

It is also possible to load the associated objects by embedding them instead of giving a reference by id.

Please see other questions on StackOverflow and example / test in ember-data projects for more example.

2
votes

Adam,

I'm starting with Ember Data myself and the confusion is usually due to its many automations/assumptions of the REST API. try:

App.ModelA = DS.Model.extend({
  name:      DS.attr('string'),
  modelB:    DS.belongsTo('App.ModelB')
});

Where the REST API returns a Model A like:

{"model_a":{"name": "Adam", "model_b_id": 2}}

Effectively and by default Ember Data tacks '_id', for any belongsTo relationship, onto the decamelized attribute name, or '_ids' to any hasMany.