How would you simplify these nested routes so there isn't duplicated code?


#1

I’m confused as to how nested routes and dynamic segments work with Ember.

Below is how I’ve defined a series of nested routes for a House. I’ve been following the pattern for defining routes using Dynamic Models guide found here: https://guides.emberjs.com/v2.15.0/routing/specifying-a-routes-model/#toc_dynamic-models

this.route('houses');
this.route('house', {path: 'houses/:house_id'}, function() {
  this.route('show', {path: 'houses/:house_id/show'},);
  this.route('level-1', function() {
    this.route('master-bedroom', {path: 'houses/:house_id/level-1/master-bedroom'});
    this.route('bathroom', {path: 'houses/:house_id/level-1/bathroom'});
    this.route('patio', {path: 'houses/:house_id/level-1/patio'});
  });
});

I don’t understand why I have to keep specifying the entire path in order to get access to the :house_id dynamic segment. If I don’t specify the entire path with the dynamic segment :house_id, then trying to access the :house_id in the params object in the model() hook returns undefined.

Is there a better way to do this?


#2

Hi @johnnyicon, it seems like there are various concepts being mixed up here. According to the router you posted here, the path for house.level-1.bathroom is /houses/:house_id/level-1/houses/:house_id/level-1/bathroom.

The house.show route also jumps out. Do you really want a /show route, or would you be better served by the house.index route?


#3

To get the the :house_id param from the parent routes, you can use paramsFor, in your case `paramsFor(‘house’). The guides mention this in a section further down on the page you linked to: https://guides.emberjs.com/v2.15.0/routing/specifying-a-routes-model/#toc_reusing-route-context. That will fix your issue with have to duplicate the paths. As @locks mentions, when you’re duplicating them like you have, you will also end up with a path that might not be what you expect it to be.


#4

Also this is a great resource for figuring out routes: ember-diagonal

You can paste your route config and see the resulting urls for each route.


#5

Thanks for your response, locks. The example above was only to illustrate that I was having to use the {path: ''} on every router entry.


#6

Thank you! This is exactly what I was looking for! I opted to use modelFor in my case as it saved me a step. Cheers!


#7

Cheers! This is definitely useful! (One wonders why this isn’t part of the Ember Inspector… :thinking:)


#8

Because you haven’t added it yet :wink: