How are relationships between related models in ember data related?

I assumed that if the model in ember-data contained an identifier related to the second model, then the identifier could also be used to establish the relation toTot to the second model object according to the problem I created here on github . This is apparently not the case.

Does anyone know the circumstances that are necessary to establish the relationship between the two objects that exist in the ember data store, are related to each other? Do I need to load related objects at the same time? (or follow the same request in the case of RESTAdapter) so that identifier links work? If they do not go through the same query, is there a way to establish relationships for subsequent queries without having to add event handlers for queries that search for relationships and set them manually? Here is an example of the problem I am 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 
+4
source share
2 answers

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

For example, for belongsTo , ember-data assumes that you send the key model_b_id with the identifier of the associated object. Then ember-data will handle the loading of this object, usually by calling the API: GET model_b/the_id

You can also load related objects by inserting them instead of specifying a link by id.

For more details, see other questions about StackOverflow and the example / test in projects with ember data.

+1
source

Adam,

I start with Ember Data on my own, and the confusion is usually related to its many REST API automation / assumptions. try:

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

If the REST API returns model A, like:

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

Effectively and by default, Ember Data tacks "_id", for any relationship, belongs to the name of the decamelated attribute or "_ids" for any hasMany.

+1
source

All Articles