Locomotive

Routing : Namespaces

Locomotive's router supports namespaces and nesting, which are used to structure routes according to a hierarchy.

Namespaces

You may want to organize an application by grouping controllers under a namespace. Most commonly, administrative functionality is grouped under an Admin:: namespace by placing controllers in the app/controllers/admin directory and declaring routes within a namespace:

this.namespace('admin', function() {
  this.resources('posts');
});

The above results in the following URLs and routing helpers being mapped to Admin::PostsController:

Method Path Action Helper
GET /admin/posts index adminPostsPath()
GET /admin/posts/new new newAdminPostPath()
POST /admin/posts create
GET /admin/posts/:id show adminPostPath(id)
GET /admin/posts/:id/edit edit editAdminPostPath(id)
PUT /admin/posts/:id update
DELETE /admin/posts/:id destroy

Each of the above path routing helpers has a corresponding URL routing helper.

Nested Resources

It is common to have resources that are logically children of other resources. These relationships can be captured in routes by nesting resources:

this.resources('bands', function() {
  this.resources('albums');
});

In addition to the routes for bands, the following URLs and routing helpers are mapped to AlbumsController:

Method Path Action Helper
GET /bands/:band_id/albums index bandAlbumsPath(bandId)
GET /bands/:band_id/albums/new new newBandAlbumPath(bandId)
POST /bands/:band_id/albums create
GET /bands/:band_id/albums/:id show bandAlbumPath(bandId, id)
GET /bands/:band_id/albums/:id/edit edit editBandAlbumPath(bandId, id)
PUT /bands/:band_id/albums/:id update
DELETE /bands/:band_id/albums/:id destroy

Each of the above path routing helpers has a corresponding URL routing helper.

While no limit is placed on the number of levels to which resources can be nested, applications are encouraged not to nest more than one level deep, as doing otherwise quickly becomes cumbersome.