ember.jsember-router

How can a child route (or resource) access a parent resource's model from within the model hook?


Seems like in the case of nested routes, each route's model hook is called before any of the setupController hooks are called. So how can a child route safely access the parent's model?

In my case, the models aren't actually persisting entities. They're both generated, based on the params, in the model hooks. So I wouldn't think a Parent.find() / ajax / promise seems like the way to go. Ideally, the parent model should be accessible through the ParentController, no? Or is this approach not in keeping with best practices?

App.Router.map(function() {
  this.resource("parent", { path: "parent/:name" }, function() {
    this.route('child');
  });
});

App.ParentRoute = Ember.Route.extend({
  model: function(params) {
    // build a model here, based on params.
    // no asynch stuff happening, should be good to go.
    return { lastName: params.name }
  },

  setupController(controller, model) {
    controller.set('model', model);
  }
});

App.ChildRoute = Ember.Route.extend({
  model: function(params) {
    parentModel = this.controllerFor('parent').get('model');
    return {lastName: parentModel.get('name') + 'son' };

    // parent Model is null
    // need the parent model HERE, 
    // but I can't get it through the controller yet
    // as setupController in the parent route hasn't been called yet
  }
});

Solution

  • modelFor

    How'd I miss that?

    App.ChildRoute = Ember.Route.extend({
      model: function(params) {
        parentModel = this.modelFor('parent');
        return {lastName: parentModel.get('name') + 'son' };
      }
    });