Redirecting Edit Page


Before the model is known

If you want to redirect from one route to another, you can do the transition in the beforeModel hook of your route handler.

1
2
3
4
5
6
7
8
9
App.Router.map(function() {
  this.resource('posts');
});

App.IndexRoute = Ember.Route.extend({
  beforeModel: function() {
    this.transitionTo('posts');
  }
});

After the model is known

If you need some information about the current model in order to decide about the redirection, you should either use the afterModel or the redirect hook. They receive the resolved model as the first parameter and the transition as the second one, and thus function as aliases. (In fact, the default implementation of afterModel just calls redirect.)

1
2
3
4
5
6
7
8
9
10
11
12
13
App.Router.map(function() {
  this.resource('posts');
  this.resource('post', { path: '/post/:post_id' });
});

App.PostsRoute = Ember.Route.extend({
  afterModel: function(posts, transition) {
    if (posts.length === 1) {
      this.transitionTo('post', posts[0]);
    }
  }
});

When transitioning to the PostsRoute it turns out that there is only one post, the current transition is aborted in favor of redirecting to the PostRoute with the single post object being its model.

Based on other application state

You can conditionally transition based on some other application state.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
App.Router.map(function() {
  this.resource('topCharts', function() {
    this.route('choose', { path: '/' });
    this.route('albums');
    this.route('songs');
    this.route('artists');
    this.route('playlists');
  });
});

App.TopChartsChooseRoute = Ember.Route.extend({
  beforeModel: function() {
    var lastFilter = this.controllerFor('application').get('lastFilter');
    this.transitionTo('topCharts.' + lastFilter || 'songs');
  }
});

// Superclass to be used by all of the filter routes below
App.FilterRoute = Ember.Route.extend({
  activate: function() {
    var controller = this.controllerFor('application');
    controller.set('lastFilter', this.templateName);
  }
});

App.TopChartsSongsRoute = App.FilterRoute.extend();
App.TopChartsAlbumsRoute = App.FilterRoute.extend();
App.TopChartsArtistsRoute = App.FilterRoute.extend();
App.TopChartsPlaylistsRoute = App.FilterRoute.extend();

In this example, navigating to the / URL immediately transitions into the last filter URL that the user was at. The first time, it transitions to the /songs URL.

Your route can also choose to transition only in some cases. If the beforeModel hook does not abort or transition to a new route, the remaining hooks (model, afterModel, setupController, renderTemplate) will execute as usual.