Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Dynamic Segments in a Single Resource in Ember.js

Is there a way to have multiple dynamic segments with a single resource? My use case is to avoid letting the user hit index routes.

Example:

this.resource('tracks', { path: 'albums/:album_id/tracks/:tracks_id' });

And I'd like to avoid the user from hitting the following routes:

albums/:album_id
albums/:album_id/tracks
albums/:album_id/tracks/:track_id

Routes:

this.resource('albums', { path: 'albums' }, function(){
  this.resource('album', { path: '/:album_id' }, function() {
    this.resource('tracks', { path: 'tracks' }, function(){
      this.resource('track', { path: '/:track_id' });
    });
  });
});

Any help would be greatly appreciated.

Defining Your Routes

NOTE: If you define a resource using this.resource and do not supply a function, then the implicit resource.index route is not created.

like image 369
alvincrespo Avatar asked Dec 05 '13 21:12

alvincrespo


2 Answers

It would be better to use Ember's nested routes. Each route having its own dynamic segment.

App.Router.map(function () {
    this.resource('albums', { path: '/albums' }, function () {
        this.resource('album', { path: ':album_id' }, function () {
            this.resource('tracks', { path: 'tracks' }, function () {
                this.resource('track', { path: ':track_id' });
            });
        });
    });
});

If you want to show the user the first track immediately after clicking an album, you could use a redirect.

App.AlbumRoute = Ember.Route.extend({
    afterModel: function (album, transition) {
        this.transitionTo('track', {album_id: album.id, track_id: album.tracks[0].id});
    },
});

Check out the docs on redirection: http://emberjs.com/guides/routing/redirection/

like image 182
hso Avatar answered Oct 19 '22 11:10

hso


Just for completeness sake, the index routes aren't necessary, they are just a freebie convenience if you define them, if you don't define them it won't go to them.

http://emberjs.jsbin.com/eMofowUQ/1/edit

And you can define multiple slugs in a single path and go directly to it, just note you'll only have a single model for that single resource, so you'll have to deal with that.

http://emberjs.jsbin.com/eMofowUQ/2/edit

like image 30
Kingpin2k Avatar answered Oct 19 '22 11:10

Kingpin2k