p1100i
p1100i

Reputation: 3740

How to define route name for nested resource in Ember.js?

I've got nested resources in my ember routes. Lets suppose according this example, that my router.js looks like:

App.Router.map(function() {
  this.resource('post', { path: '/post/:post_id' }, function() {
    this.resource('comment', { path ':comment_id' });
  });
});

The documentation says this should generate routes like:

/post/:post_id              post.index
/post/:post_id/:comment_id  comment.index

However I would like these to be post.show and comment.show, how do I rename these routes?

Upvotes: 2

Views: 1020

Answers (1)

Marcio Junior
Marcio Junior

Reputation: 19128

I have get this working with the following setup.

Routers with dynamic segment:

App.Router.map(function() {
    this.resource('post.show', { path: '/post/:post_id' });
    this.resource('comment.show', { path: '/post/:post_id/:comment_id' });
});

Overriding the serialize hook of App.CommentShowRoute to reflect the url expected:

App.CommentShowRoute = Ember.Route.extend({
    serialize: function(model) {       
        return {           
            post_id : model.get("post_id"),
            comment_id : model.get("id")
        };
    }
});

The major problem implementating this is the url generated, since the model in the serialize hook, isn't loaded, the post_id property isn't present, and after the model is loaded this isn't automatically updated. So a linkTo targeting a comment will have a url post/undefined/1, instead of post/1/1. Clicking in the link works, because after some time the model is loaded, but if the user refresh the page, will not work, because of the wrong url.

To fix it, I used the 3 approach from this discussion forum comment, where we use the action helper instead of linkTo. The only diference is that the link will not have the href` property with the url, but when clicking all works.

The result is that:

App.PostShowRoute = Ember.Route.extend({
    events : {
        goToComment: function(context){
            this.transitionTo('comment.show', context);
        }
    }
});

Here is a demo with the full implementation.

Upvotes: 1

Related Questions