[SOLVED] How to connect routes & models?


#1

Hi there,

I have a small Ember-Data app using DRFAdapter that allows me to list some shipments and to display a single one determined by its id. Just two routes.

this.route('shipments');
this.route('shipment', { path: '/shipments/:shipment_id' }

Both are backed by an API with the following endpoints:

.../v1/shipments/
.../v1/shipments/123456/

This works like a charm but now I want to fetch some more data that belongs to a single record. API endpoint for this is

.../v1/shipments/123456/events/

I already tried to expand my shipment model by

events: DS.hasMany('event', { async: true }),

but this doesn’t do the trick. Get back an empty DS.PromiseArray, cant see any network request. So I must miss some piece to start the magic. Do I need another route? Just want to add the events to the existing detail page of the shipment. Relation between shipment and events is pretty much like between blog post and comments…

Sorry for being stupid & thanks in advance, Martin

Solved with nested routes.

this.route('shipments');
this.route('shipment', { path: '/shipments/:shipment_id' }, function() {
  this.route('events', {});
});

In the events route I get the model instance from the parent route (‘shipment’), extract the needed id from there and ask for the events like so:

// get model instance from parren route (shipment)
const shipment = this.modelFor('shipment');

// ask the orm for events of shipment with shipment.id
// attention! we need to customize the url for the adapter!!!!!
return this.store.query('event', { param: shipment.id });

Finally I had to tweak the adapter to assemble the url my API expects:

urlForQuery: function(query, modelName) {

    // var url = this._super(query, modelName);
    // We could get the url from super to re-assemble their parts in a manner 
    // the API does like. However, as we know the URL scheme pretty well, we
    // cut short here...

    return 'https://yadayada/v1/shipments/' + query["param"] + '/events';

}

Hope this helps. I just got a little smarter! :slight_smile:

M.

P.S. Credits to Ember Igniter


#2

Do you have an events model and adapter?


#3

Yes, I am using a shipment model and an event model. I am also using an adapter (DRFAdapter using the DataAdapterMixin for auth).