Search code examples
node.jsexpresscompoundjs

CompoundJs, ExpressJs routes


I have NodeJs : 0.10.22 and compoundJs : 1.1.7-11

I have following Controller code:

module.exports = Rose;

function Rose(init){

}

Rose.prototype.index = function(c){
    c.send('Controller ROSE,  Function Index');
};

Rose.prototype.thorne = function thorne(c){
    c.send('Controller ROSE, Function Thorne');
};

I have defined following route in routes.js file :

exports.routes = function (map) {

    map.resources('rose', function(flower){
         //flower.get('thorne', '#thorne');
        flower.get('thorne');
    });
};

I have tried both lines in map.resources (one is currently remarked, but earlier it was used) in routes.js.

Following url works :

http://localhost:3000/rose

But following url doesn't work:

http://localhost:3000/rose/thorne

And it shows Following error:

Express
500 Error: Undefined action rose#show(/rose/thorne)

Can some one guide me what I am doing wrong and how it can be rectified.


Solution

  • CompoundJS CRUD allows a list of a model to be viewed, and methods to manipulate individual data. When using .resources, several routes are generated. You can view them by running compound routes (or compound r for short). Some examples below using roses (plural):

    roses GET        /roses.:format?          roses#index - Should return a list of roses
    rose GET         /roses/:id.:format?      roses#show  - Displays a single rose
    edit_rose GET    /roses/:id/edit.:format? roses#edit  - Brings up an edit form for a single rose
    

    When mapping the route for a flower, compoundjs expects you to map a flower to one single rose. The route is defined as:

    thorne_rose GET  /roses/:rose_id/thorne   roses#thorne
    

    You have to pass in a rose id to access that particular rose's thorne. However, if you intend to only have one rose (no list of roses or anything), you can add the singleton option to the resource:

    map.resources('rose', { singleton: true }, function(flower) {
        flower.get('thorne');
    });
    

    This will also eliminate the index route, instead use Rose.prototype.show. In a typical CRUD, the index lists all of the values for in the model. Since there is only one value, a list page is not needed.