Search code examples
ember.jsember-router

How to get children for current object in ember route


The templates section in the Ember guides describes how to use the linkTo helper. However, I can't seem to find the answer to my following question:

I have a page displaying some properties of a Post object. The page contain a link 'Comments' that need to display the comments that belong to the current post.

// Router
App.Router.map(function(match) {
  match('/posts').to('posts', function(match) {
    match('/:post_id').to('post', function(match) {
      match('/').to('postIndex');
      match('/comments').to('comments');
    });
  });
});

// post template
...
{{#linkTo "comments"}}Comments{{/linkTo}}
...
{{outlet}}

How do I need to define my CommentsRoute to populate the content of the controller with the comments of the current post?

App.CommentsRoute = Ember.Route.extend({
  model: function() {
    // I need to get the content of the postController here
    // this.controllerFor('post') seemed obvious, but doesn't work
    post = ????;
    post.get('comments')
  }
})

Thanks in advance.


Solution

  • You can access the postController with controllerFor from within routes:

    App.CommentsRoute = Ember.Route.extend({
      model: function() {
        var controller = this.controllerFor('post');
        return controller.get('comments');
      }
    });
    

    Are you using ember-data? In that case, it might make sense to sideload the comments data when loading the post data. https://github.com/emberjs/data/blob/master/BREAKING_CHANGES.md#revision-11

    UPDATE: Chanted get('comments') to get('comments.content')

    UPDATE: Reverted get('comments')