Rails Scaffold

Collapse Content

Rails provides a built-in scaffold tool that lets you quickly create a Model, Controller, View and Routes all at once. We didn't cover it in main course since it's easier to initially understand how Rails works without using a scaffold. Also, you'll often need to customize the scaffold's generated code so that it doesn't actually end up saving time.

However, in some cases you'll create a MVC with a very 'standard' structure, so the scaffold can be a convenient shortcut to get started. We're creating a blog application, which means users should be able to Create, Read, Update and Delete their Posts (CRUD). There will be specific pages for viewing each post, viewing a list of posts, and creating and updating posts. This structure aligns with the scaffold's, so let's use the scaffold to get started. Just like when creating a model, we need to tell Rails what column to add to Post. For now, we'll just use one content column to store the actual content of each post. Enter the following in the terminal:

rails generate scaffold Post content:text

This will generate output showing you everything it creates, some of which you can see below.

invoke  active_record
      create    db/migrate/20150708213110_create_posts.rb
      create    app/models/post.rb
      invoke  resource_route
       route    resources :posts
      invoke  scaffold_controller
      create    app/controllers/posts_controller.rb
      invoke    erb
      create      app/views/posts
      create      app/views/posts/index.html.erb
      create      app/views/posts/edit.html.erb
      create      app/views/posts/show.html.erb
      create      app/views/posts/new.html.erb
      create      app/views/posts/_form.html.erb

Just like when you generated a model on its own, scaffold created a migration file for creating the actual database table. Enter the following to run the migration and create the table:

rake db:migrate

Now go back to your browser and open /posts. You can now CRUD posts! Play around by creating posts and viewing them.

(Note: If you terminated you're rails server, first enter rails s to to restart it.)

Contact Us
Sign in or email us at [email protected]