How Rails Generators Make CRUD Workflow Go Smoother

Nora LC
2 min readDec 21, 2020
Photo by Michael Hodgson, New York 2019

Ruby on Rails or Rails is a user-friendly open source framework. Its main goal is to optimize the web application development process.

Rails developers must follow standard best practice conventions in order for the magic to happen. Rails is built on the principle of convention over configuration (for example: a model is singular — a controller is plural).

Generators are a nifty way of integrating standard features that help creating CRUD functionalities in an application. So instead of having to build them manually each time, Rails came out with a faster automated way. Let’s break this more down by running rails g in the command line of a rails application:

General options:
-h, [--help] # Print generator's options and usage
-p, [--pretend] # Run but do not make any changes
-f, [--force] # Overwrite files that already exist
-s, [--skip] # Skip files that already exist
-q, [--quiet] # Suppress status output
Please choose a generator below.Rails:
application_record
assets
channel
controller
generator
helper
integration_test
jbuilder
job
mailbox
mailer
migration
model
resource
scaffold
scaffold_controller
system_test
task
ActiveRecord:
active_record:application_record
TestUnit:
test_unit:channel
test_unit:generator
test_unit:mailbox
test_unit:plugin

We see a list of all built-in generator, from application record to task . If we want to generate any of them, all we need is run rails g (name of generator we want to generate).

Let’s compare two of the most common commands. rails g resource vs rails g migration . I personally consider the first one to be the smartest of all. For example, running rails g resource SignUp username id_number:integerwould mainly create the following:

  • A migration file with the proper name/path: /db/migrate/20201221141414_create_sign_ups.rb, as well as the corresponding attributes:
class CreateSignUps < ActiveRecord::Migration[6.0]   def change       create_table :sign_ups do |t|         t.string :username         t.integer :id_number         t.timestamps       end    endend
  • A model file that inherits from ApplicationRecord
class SignUp < ApplicationRecordend
  • A controller file that inherits from ApplicationController
  • A view directory
  • A full resources call in the routes.rb file

On the other hand, for example, we can add a new table to a data base by running rails g migration <SignUp> . This create the migration file ‘’######_sign_up.rb

class SignUp < ActiveRecord::Migration[6.0]   def change   endend

Our take on this: Rails generators follow Rails best practices, which includes utilizing RESTful naming patterns.

Lastly, Rails generators can be reversed by replacing g with d . For example, in our SignUp migration example, we could run rails d migration <SignUp> .

--

--