dechov
dechov

Reputation: 1833

Proper way to use parent route parameters with ember-data?

In my app, I am trying to keep the routing structure as close to the API structure as possible, which ember facilitates in the basic case but I am still confused about the following case:

(In reference to the example of http://emberjs.com/guides/outlets/#toc_nesting)

What is the best way to go about retrieving the /posts/:post_id/comments data (assuming it isn't given to me by /posts/:post_id)?

Should I be passing the post ID to App.Comment.find(...) somehow, in the comments.deserialize(...) method? Is there a better way to get the post ID than router.getPath('postController.content._id')? I am using a modified DS.RESTAdapter.

Upvotes: 2

Views: 1522

Answers (1)

Mike Aski
Mike Aski

Reputation: 9236

Parent router parameters are no more accessible as parameters in children routes, but should have been used to retrieve and populate intermediate data structure.

Given your models are defined as follow:

App.Post = DS.Model.extend({
  text: DS.attr('string'),
  // ...
  comments: DS.hasMany('App.Comment')
});

App.Comment = DS.Model.extend({
  // You may also have: "post: DS.belongsTo('App.Post')", but we do not care for this exemple
  text: DS.attr('string'),
  // ...
});

This should be something working:

posts: Ember.Route.extend({
  route: 'posts',

  member: Ember.Route.extend({
    route: '/:post_id', // [A]

    connectOutlets: function (router, post) {
      var applicationController = router.get('applicationController');
      applicationController.connectOutlet('post', post); // [B]
    },

    show: Ember.Route.extend({
      route: '/'
    }),

    comments: Ember.Route.extend({
      route: 'comments',

      connectOutlets: function (router) {
        var postController = router.get('postController'),
            comments = postController.get('comments'); // [C]
        postController.connectOutlet('comments', comments);
      },
    }),
  })
})
  • [A]: The post model instance will be retrieved automagically by the router, according to convention: post_id refers to Post model instance with the given id (see this comment).
  • [B]: Here, PostController will be populated by the router with the passed context: post, which is the Post instance retrieved upper (see [A]).
  • [C]: PostController is an ObjectController (i.e Proxy) on the post model instance, so it directly holds comments.

Upvotes: 5

Related Questions