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.

Note
This post is mostly a reference for me and is not a deep dive. It may or may not make sense to you without some experiense with Rails.

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.

cmd
rails generate controller PluralizedName [list of actions] [list of --options]

Controller generators create a number of files and also update the routes file.

cmd
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
file
# app/controllers/services_controller.rb
class ServicesController < ApplicationController
  def index
  end

  def show
  end
end

Models

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.

Model DB Table
Device devices
ServiceContract service_contracts

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

cmd
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.

cmd
rails generate model Device name:string description:text

file
# app/models/role.rb
class Role < ApplicationRecord
end
file
# 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
end

Migrations

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.

cmd
rails generate migration NAME [list of field[:type][:index]] [list of --options]

Create a Table

Create a complete migration with the following command.

cmd
rails generate migration CreateMacAddresses mac_address:macaddr description:string

This generates the following migration file.

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
end

Add 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.

cmd
rails generate migration AddDescriptionToRoles description:text

This generates the following migration file.

file
# db/migrate/<timestamp>_add_description_to_roles.rb 
class AddDescriptionToRoles < ActiveRecord::Migration[6.0]
  def change
    add_column :roles, :description, :text
  end
end

Remove 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.

cmd
rails generate migration RemoveDescriptionFromRoles description:text

This generates the following migration file.

file
# db/migrate/<timestamp>_remove_description_from_roles.rb 
class RemoveDescriptionFromRoles < ActiveRecord::Migration[6.0]
  def change
    remove_column :roles, :description, :text
  end
end

Rename a Column

First create a migration

cmd
rails generate migration ChangeMacAddressesColumn

The 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

file
# db/migrate/<timestamp>_change_mac_addresses_column.rb 
class ChangeMacAddressesColumn < ActiveRecord::Migration[6.0]
  def change
    rename_column :mac_addresses, :mac, :mac_address
  end
end

One to Many Association

Create a migration to associate rooms with a site.

cmd
rails generate migration AddAssociationToRooms site:references

The following completed migration will be generated.

file
# 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
end

Now you need to update the models with the has_many and belongs_to properties.

A site has_many rooms (plural)

file
# db/models/site.rb 
class Site < ApplicationRecord
  has_many :rooms, dependent: :destroy
end

A room belongs_to a site (singular).

file
# db/models/room.rb 
class Room < ApplicationRecord
  belongs_to :site
end

Delete a Table

First create a migration

cmd
rails generate migration DropRoles

The above command will generate an empty change migration file. Add the following code to rename the column.
drop_table :table_name

file
# db/migrate/<timestamp>_drop_table.rb 
class DropRoles < ActiveRecord::Migration[6.0]
  def change
    drop_table :roles
  end
end

Reverse a Generator

Reversing a generator is possible using the following command.

cmd
rails destroy GENERATOR [args] [options]

Some examples below.

cmd
rails destroy controller Devices
rails destroy model Device
rails destroy migration AddDescriptionToDevices

Outro

Rails generators are super powerful. Use them responsibily.

# rails
# ruby