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

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: Specifying a Route's Model - Routing - Ember Guides

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?

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?

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: Specifying a Route's Model - Routing - Ember Guides. 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.

2 Likes

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.

1 Like

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

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!

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

Because you haven’t added it yet :wink:

1 Like