Inspect child route from parent route


#1

Is is possible to inspect a child route/the url of an app from a parent route? My parent routes contain lists of items and I want to transition to/select the first item in the list automatically if an item isn’t already selected. As an example:

Given URL /parent/10/ with the following router and routes:

App.Router.map(function () {
   this.resource('parent', function () {
      this.route('detail', { path: ':item_id' });
   });
});

App.ParentRoute = Ember.Route.extend({
   model: function () {
      return this.store.find('item');
   },

   setupController: function (controller, model) {
      controller.set('model', model);
      // somehow set this to the selectedObject (/10 in the above url) if present
      var selected = controller.get('sortedContent').get('firstObject');
      this.transitionTo('parent.detail', selected);
   }
});

App.ParentDetailRoute = Ember.Route.extend({
   model: function(params) {
      return this.get('item', params.item_id);
   }
})

My problem right now is /parent/10/ and /parent/ both end up at /parent/1/ because of the way selected is currently set. Is there a way to see if the URL has a slug attached and transition to that if present?


#2

Did u explore redirect option on the Router ?


#3

@gurumurthy_dine I know of the hook but I haven’t yet found a way to examine a part of the child route from the parent route. It might be dead simple but I didn’t see anything in the docs referencing it and I haven’t had any luck Googling for it.


#4

The thing to keep in mind in a situation like this is the fact that an index route is implicitly created. So, what your map actually looks like is this:

  App.Router.map(function() {
    this.resource('parent', function() {
      this.route('index'); // Implicitly created
      this.route('detail', {path: ':item_id'});
    });
  });

When entering the parent route, the index route will be automatically entered if no other child-to-parer route is entered. So it’s in that index route that you’ll want to handle the transitionTo.

So, all you’ll need is this:

  App.ParentIndexRoute = Ember.Route.extend({
    beforeModel: function() {
      this.transitionTo('parent.detail', this.modelFor('parent').get('firstObject'));
    }
  });