Search code examples
javascriptember.jsember-router

How do I disambiguate nested routes in ember.js?


I have two resources that both have the same sub-resource:

App.Router.map(function() {
  this.resource('post', function() {
    this.resource('comments', function() {
      this.route('new');
    });
  });

  this.resource('product', function() {
    this.resource('comments', function() {
      this.route('new');
    });
  });
});

The problem is that the ember router builds the names of the route objects out of just the current and parent routes, not out of the whole hierarchy. Thus, it tries to route both /posts/:id/comments/new and /products/:id/comments/new to the App.NewCommentRoute object. What can I do to fix this?

This post was adapted from a GitHub issue.


Solution

  • I took James A. Rosen's solution one step further and it worked like a charm. A bit redundant, but makes things much more intuitive down the road:

    App.Router.map(function() {
      this.resource('post', function() {
        this.resource('post.comments', { path: '/comments' }, function() {
          this.route('new');
        });
      });
    
      this.resource('product', function() {
        this.resource('product.comments', { path: '/comments' }, function() {
          this.route('new');
        });
      });
    });
    

    This now allows you to use transitionTo('product.comments.new') or App.register('route:product.comments.new', myRouteHandler) just as originally expected.

    If you don't manually register your route handler, Ember, gracefully, will even look for it in App.ProductCommentsNewRoute

    The only downside is the redundancy of defining the name of the sub-resource with the same root name that the parent resource already has.