Search code examples
ember.jsember-router

EmberJS: Allow Optional ID in Resource


Using Emberjs, I would like to follow the REST specification, whereby an array of all objects is returned when no id is specified:

  • http://localhost:4200/database returns all databases (would be databases)
  • http://localhost:4200/database/:id returns the database info for a provided database (as expected)

My routes are defined as follows:

Router.map ->
    @resource "database", ":database_id", ->
        @route "new"
        @route "edit"

How can I allow for an optional id in my resource?


Solution

  • Im not the biggest fan of CoffeeScript so ill be replying with good old JavaScript.

    So your routes look wrong, they should be as follows

    App.Router.map(function() {
       this.resource("databases", function() {
           this.route("new"),
           this.resource("databases", { path: '/databases/:id' }, function() {
              this.route("edit"),
           });
       });
    });
    

    this would give you the following,

    /databases (list of databases )
    /databases/new  ( create a new database )
    /databases/:id  ( view a database with id :id)
    /databases/:id/edit  (edit the database with id of :id )
    

    this removes the need for needing an optional ID.