Rails Generators Cheat Sheet
Updated: 2020-12-06
Published: 2020-12-03
Overview
As I am digging into Rails again I find myself constantly having to look the naming and syntax of generators up so I am documenting them in this post.
Rails utilizes convention over configuration to speed up development and increase developer happiness. If you embrace this fact you will be alot happer working wih rails. This means that the folders are structured in a certain way and the files/classes/methods need to be named to an opinionated standard. This is to enforce best practices and assist with auto-loading.
Controllers
Naming Conventions
Controllers favour pluralization for Controller names.
Singular words are capitalized: Devices.
Multiple word controllers should use CamelCase, with only the last word pluralized: ServiceContracts
Generators
When using the controller generator you define the pluralized controller name with an optional list of actions and options.
Controller generators use the following syntax.
rails generate controller PluralizedName [list of actions] [list of --options]Controller generators create a number of files and also update the routes file.
rails generate controller Devices index show
# output
create app/controllers/services_controller.rb
route get 'services/index' get 'services/show'
create app/views/services
create app/views/services/index.html.erb
create app/views/services/show.html.erb
invoke test_unit
create test/controllers/services_controller_test.rb
invoke helper
create app/helpers/services_helper.rb
invoke test_unit
invoke assets
invoke css
create app/assets/stylesheets/services.css# app/controllers/services_controller.rb
class ServicesController < ApplicationController
def index
end
def show
end
endModels
Naming Conventions
Models favour singular words for the model name.
Singular words are capitalized: Device.
Multiple word models should use CamelCase: ServiceContracts
Model to Database Tables Naming
Singular CamelCase model names map to pluralized snake_case database table names.
Generators
When using the model generator you define the singular model name with an optional list of field:type references and options.
The list of supported types can be found here.
Model generators use the following syntax
rails generate model SingularName [list of field[:type][:index]] [list of --options]Model generators create a model file as well as the database migration file.
rails generate model Device name:string description:text# app/models/role.rb
class Role < ApplicationRecord
end# db/migrate/<timestamp>_create_roles.rb
class CreateRoles < ActiveRecord::Migration[6.0]
def change
create_table :roles do |t|
t.string :name
t.text :description
t.timestamps
end
end
endMigrations
Naming Conventions
Migrations names should use CamelCase: CreateMacAddressTable
Generators
Migrations generators have some special conventions that allow for conventient creation of migration files.
Migration generators use the following syntax.
rails generate migration NAME [list of field[:type][:index]] [list of --options]Create a Table
Create a complete migration with the following command.
rails generate migration CreateMacAddresses mac_address:macaddr description:stringThis generates the following migration file.
# db/migrate/<timestamp>_create_mac_addresses.rb
class CreateMacAddresses < ActiveRecord::Migration[6.0]
def change
create_table :mac_addresses do |t|
t.macaddr :mac_address
t.string :description
end
end
endAdd a Column
If the migration name includes the phrase AddColumnToTable and is followed by a list of name:type values a complete migration will be generated.
rails generate migration AddDescriptionToRoles description:textThis generates the following migration file.
# db/migrate/<timestamp>_add_description_to_roles.rb
class AddDescriptionToRoles < ActiveRecord::Migration[6.0]
def change
add_column :roles, :description, :text
end
endRemove a Column
If the migration name includes the phrase RemoveColumnFromTable and is followed by a list of name:type values a complete migration will be generated.
rails generate migration RemoveDescriptionFromRoles description:textThis generates the following migration file.
# db/migrate/<timestamp>_remove_description_from_roles.rb
class RemoveDescriptionFromRoles < ActiveRecord::Migration[6.0]
def change
remove_column :roles, :description, :text
end
endRename a Column
First create a migration
rails generate migration ChangeMacAddressesColumnThe above command will generate an empty change migration file. Add the following code to rename the column. rename_column :table_name, :old_column_name, :new_column_name
# db/migrate/<timestamp>_change_mac_addresses_column.rb
class ChangeMacAddressesColumn < ActiveRecord::Migration[6.0]
def change
rename_column :mac_addresses, :mac, :mac_address
end
endOne to Many Association
Create a migration to associate rooms with a site.
rails generate migration AddAssociationToRooms site:referencesThe following completed migration will be generated.
# db/migrate/<timestamp>_add_association_to_rooms.rb
class AddAssociationToRooms < ActiveRecord::Migration[6.0]
def change
add_reference :rooms, :site, null: false, foreign_key: true
end
endNow you need to update the models with the has_many and belongs_to properties.
A site has_many rooms (plural)
# db/models/site.rb
class Site < ApplicationRecord
has_many :rooms, dependent: :destroy
endA room belongs_to a site (singular).
# db/models/room.rb
class Room < ApplicationRecord
belongs_to :site
endDelete a Table
First create a migration
rails generate migration DropRolesThe above command will generate an empty change migration file. Add the following code to rename the column. drop_table :table_name
# db/migrate/<timestamp>_drop_table.rb
class DropRoles < ActiveRecord::Migration[6.0]
def change
drop_table :roles
end
endReverse a Generator
Reversing a generator is possible using the following command.
rails destroy GENERATOR [args] [options]Some examples below.
rails destroy controller Devices
rails destroy model Device
rails destroy migration AddDescriptionToDevicesOutro
Rails generators are super powerful. Use them responsibily.
Links
https://guides.rubyonrails.org/getting_started.html
https://guides.rubyonrails.org/association_basics.html
https://guides.rubyonrails.org/action_controller_overview.html
https://devtut.github.io/rubyonrails/naming-conventions.html
https://medium.com/nerd-for-tech/rails-generators-cheat-sheet-61e2e58b7be7
https://medium.com/@kevinyckim33/rails-generators-cli-cheatsheet-711295e7a1ed
https://blog.yechiel.me/generating-belongs-to-associations-in-rails-be7b7fdea96c