Scaffold Generator in Rails

If you are new to Rails, you might come across Scaffold generator. So what is scaffold generator in Rails? In this blog post, I will show you a code along with an example of how to use it.

First, What is Scaffold?

Scaffolding, also called scaffold or staging is a temporary structure used to support a work crew and materials to aid in the construction, maintenance and repair of buildings, bridges and all other man-made structures.” — Wikipedia

Now that you know what scaffold is in general, you can have an idea of what scaffold is in Rails. A scaffold in Rails is a generator that can be used in the command line to automatically generate some files to create the basic structure of a complete Rails application. These files include a Model, a Controller, Views for each controller action, a Migration for the database, a Route, and some test unit files.

Let's start our code along!

First, let’s try out this generator to create a movie project. In your terminal, run first $ rails new movies to create the project then run $ rails generate scaffold moviesto create the basic structure. Here is the result of running the scaffold generator:

That command created the following for us:

  • A movie model
  • A movie controller
  • A new route resources :movies that was added to config/routes.rb.
  • Views inside app/views.movies
  • Some testing files

Let’s undo this by using the destroy command, $ rails destroy scaffold movies.

This deleted everything that was created when you ran the scaffold generator command.

Let’s re-run the scaffold generator command, but now let’s add some fields:

$ rails generate scaffold movies title:string director:string

Now remember one thing, this created a migration file for you for the database, however, you still need to run $ rails db:migrate to migrate the database changes. If you don’t see any errors, then you are ready to run your application on your browser.

Running the application on your browser

Now that we’ve created our application, let’s try to run it on the browser. To do so, you need to run the rails server. In your terminal, run the following command:

$ rails server

You can check out the application by directing to: http://localhost:3000/movies

If you click on the ‘New Movie’ link, you can create a new movie like showing below:

Play around with the application and try to add more movies and delete some movies and edit them as well.

This was an explanation of how to use the Scaffold generator in rails. If you have anything you would like to add, please comment below!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store