Forward Advance Learning

Scaffolding and CRUD

The Scaffold Generator allows us to create a controller, model, views, partials, stylesheets and tests with a single call.

In this section we are going to look at using scaffolding to create a CRUD app in double quick time.

Scaffold the resource

It's traditional to make a blog, but feel free to make a kitten, or similar.

First create a BlogPost scaffold and give it some attributes. You can use the following generator as a jumping off point. You will need to add a content:text and probably also a date:datetime too.

rails g scaffold blog_post title:string

Look over the controller

Take a look at the controller that was made, you will find 7 standard actions allowing you to create, edit, show, index and destroy (edit and create get two methods each).

Spend a few minutes reading through the code and understanding it.

Look at the routes

You will find one line has been added to the routes file, resources.

This single line generates all of the crud routes for you. Check them out from a console by typing:

rake routes


Look at the views. See the form partial? It's used by the new and edit templates. Have a read and try to understand what's going on.


The tests that have been built for you should work right out of the box. Run:

rake test

to run all of the tests.

Exercise: Create a scaffold

For your first job create a scaffold for a domain of your choosing. For example, shipping.

Run the scaffold generator as follows:

rails g scaffold ship title:string age:integer

Further Exercise: Homepage

Set blog_post#index as the homepage, so when you visit your Blog, you see a list of entries.

Further Exercise: Create a second Scaffold

Scaffold a second model.

Now create a tab bar as a partial to allow you to swap between scaffolds. Add it to your application.html.erb partial.

You now have a little application with two models. We will hook them together in the next section.

Very nice.