Search code examples
ruby-on-railsruby-on-rails-3scaffolding

Understanding Scaffolding in Rails Better


I've read the rails guides but there are some things that when I actually do it myself I still do not understand.

For example, how come when I visit my show view on localhost I get an error? Scaffolding created a show action in my controller that is empty and a view but still get an error message.

Similar thing happens with index.

Isn't the purpose of scaffolding to help you with all this? I assumed if I made a few posts that the index action would take me to an index of all the posts but it doesn't instead the post/ itself lists them all. What is the logic behind scaffolding doing this?

EDIT::::

This is the error message that I get:

ActiveRecord::RecordNotFound in ExperimentsController#show
Couldn't find Experiment with id=index

This happens when I visit http://localhost:3000/experiments/index


Solution

  • You are accessing the routes incorrectly. To visit the index page : you need url http://localhost:3000/experiments

    When you specify url : http://localhost:3000/experiments/index, Rails would match it to the route of show page(as shown below): /experiments/:id

    If you read the error carefully:

    ActiveRecord::RecordNotFound in ExperimentsController#show Couldn't find Experiment with id=index

    Rails mapped the url to show action and is trying to find an experiment with id=index which obviously does not exist and you get an error.

    Run rake routes on command prompt and you'll see the routes created for resource experiment as follows:

               /experiments             index      display a list of all experiments
    GET        /experiments/new         new        return an HTML form for creating a new experiment
    POST       /experiments             create     create a new experiment
    GET        /experiments/:id         show       display a specific experiment
    GET        /experiments/:id/edit    edit       returns an HTML form for editing an experiments
    PATCH/PUT  /experiments/:id         update     update a specific experiment
    DELETE     /experiments/:id         destroy    delete a specific experiment
    

    You can access the specific routes with the paths shown above. Replace :id with an existing experiment records id attribute value.

    For eg:

    To view an experiment with id 5 Visit http://localhost:3000/experiments/5

    NOTE: I would highly recommend you to go through the Rails Routing Guide and get a better idea of how Routing works.