# Rails Database Migrations Cheatsheet

*Published on August 31, 2023*

---


Rails provides a ton of different ways to modify the database schema via Active Record migrations. It's a very powerful and flexible way to handle schema changes while keeping all updates under version control. However, all the migration methods, options, conventions, and their variations can be overwhelming, and hence, confusing.

I found myself reaching out for the&nbsp;[Rails migration guide](https://guides.rubyonrails.org/active_record_migrations.html)&nbsp;and the&nbsp;[Rails API](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column)&nbsp;almost every time I wanted to create a new Rails migration to make database changes. So last night I decided to spend a few hours to note down all the common database operations I use most of the time.

Now, this is not an exhaustive reference of ALL the methods and options. You'll still need to refer to the Rails API for the obscure ones. I've just listed the stuff&nbsp;**I use most of the time**, but I'm sure many of you will find it useful, too.

## Table of Contents

- Generating Migrations
- Migration Structure
- Applying Migrations
- Revert (Rollback) a Migration
- Common Rails Database Commands
- Working with Tables
- Create Table
- Update Table
- Rename Table
- Drop Table
- Referencing Other Tables
- Working with Columns
- Create Column
- Update Column
- Rename Column
- Drop Column
- Working with Indexes (Indices)
- Create Index
- Rename Index
- Drop Index

Sounds fun? Let's begin...

* * *

## Generating Migrations

To generate a database migration, use the&nbsp;`rails generate migration`&nbsp;command.

```ruby
$ rails generate migration CreateCustomers name:string email:string
      invoke  active_record
      create    db/migrate/20230829033126_create_customers.rb
```

After running this command, Rails will add the new migration in your project's&nbsp;`db/migrate`&nbsp;directory. Each migration filename contains a timestamp that Rails uses to determine the order of the migrations.

```ruby
# db/migrate/20230829033126_create_customers.rb

class CreateCustomers < ActiveRecord::Migration[7.1]
  def change
    create_table :customers do |t|
      t.string :name
      t.string :email

      t.timestamps
    end
  end
end
```

When you create a new table, Rails will add&nbsp;`t.timestamps`&nbsp;at the end of the definition. It adds two columns to the table:&nbsp;`created_at`&nbsp;and&nbsp;`updated_at`.

In the above command, we provided&nbsp;`CreateCustomers`&nbsp;as the name of the migration. Typically, Rails will try to guess the name of the table using the name of the migration, i.e.&nbsp;`customers`&nbsp;in this case. If Rails can figure out the table name from the migration name, it will pre-fill the generated migration file with the specified table. Otherwise, you can simply edit the migration to specify the table name.

## Migration Structure

The migration file contains a&nbsp;`change`&nbsp;method, which is used to add new tables, columns, or indexes to your database. In this method, you can use the&nbsp;`TableDefinition`&nbsp;object to create and modify tables.

In this example, we're creating the&nbsp;`customers`&nbsp;table with two string columns named&nbsp;`name`&nbsp;and&nbsp;`email`. By default, Rails also adds the&nbsp;`created_at`&nbsp;and&nbsp;`updated_at`&nbsp;columns with the&nbsp;`timestamps`&nbsp;methods.

```ruby
# db/migrate/20230829033126_create_customers.rb

class CreateCustomers < ActiveRecord::Migration[7.1]
  def change
    create_table :customers do |t|
      t.string :name
      t.string :email

      t.timestamps
    end
  end
end
```

## Applying Migrations

Once you're satisfied with the migration code, you've to run that migration. To run the newly created migration (or all outstanding migrations), run the&nbsp;`rails migrate`&nbsp;command:

```bash
$ rails migrate
```

To verify which migrations have been already applied, use the&nbsp;`rails db:migrate:status`&nbsp;command:

```bash
$ rails db:migrate:status

database: storage/development.sqlite3

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20230829171000  Create customers
```

## Revert (Rollback) a Migration

If you made a mistake, or noticed a typo in the migration that you just ran, use the&nbsp;`db:rollback`&nbsp;command to roll back the previous migration. This command reverts the schema back to the previous version.

```bash
bin/rails db:rollback
```

You can roll back a specific number of migrations by providing the&nbsp;`STEP`&nbsp;option to the&nbsp;`rollback`&nbsp;command. For example, the following command will roll back the last five migrations:

```bash
rails db:rollback STEP=5
```

After fixing the related migrations, you've to migrate the database again by running the&nbsp;`db:migrate`&nbsp;command.

**Roll Back and Migrate Using A Single Command**

The&nbsp;`db:migrate:redo`&nbsp;command will roll back the database one migration and re-migrate the database.

```bash
bin/rails db:migrate:redo
```

As with the&nbsp;`rollback`&nbsp;command, you can roll back and migrate a specific number of migrations by passing the&nbsp;`STEP`&nbsp;option to the&nbsp;`redo`&nbsp;command. The following command will roll back and re-migrate the last five migrations:

```bash
bin/rails db:migrate:redo STEP=5
```

The&nbsp;`db:migrate:reset`&nbsp;command drops and recreates all databases from their schema for the current environment and loads the seeds. This command effectively re-creates your entire database.

```bash
bin/rails db:reset
```

## Common Rails Database Commands

You can see all the available commands in Rails by running the&nbsp;`bin/rails --help`&nbsp;command. To narrow down the database-related commands, grep it on the database prefix, i.e.&nbsp;`bin/rails --help | grep db`. Here're the common ones.

```bash
# Create the database from DATABASE_URL or config
bin/rails db:create

# Load the seed data from db/seeds.rb
bin/rails db:seed

# Create databases, load schema and seed data
bin/rails db:setup

# Same as setup, but drop databases first
bin/rails db:reset

# Run setup if database doesn't exist, otherwise migrate
bin/rails db:prepare

# Generate a migration
bin/rails generate migration CreateCustomers name:string:index email:string

# Migrate the database
bin/rails db:migrate

# Show status of migrations
bin/rails db:migrate:status

# Revert (rollback) the previous (n) migration(s)
bin/rails db:rollback STEP=n

# First rollback, then migrate previous (n) migration(s)
bin/rails db:migrate:redo STEP=n
```

For a detailed overview of these tasks, please refer to this blog post: [All the Database Tasks in Rails](/rails-database-tasks)

## Naming Conventions for Active Record Migrations

You can flesh out the structure of the migration during generation by following a few simple conventions. Here're the most common ones I've found. If you know more, let me know in the comments.

```bash
# Creates a table named 'Table' with provided columns
bin/rails g migration CreateTable col:type col:type

# Adds column 'Column' to table 'Table'
bin/rails g migration AddColumnToTable col:type

# Removes column 'Column' from table 'Table'
bin/rails g migration RemoveColumnFromTable col:type

# Adds the `amount` column on the `carts` table with precision 10 and scale 2, and
# adds the `user_id` column on the `carts` table (cart references user)
bin/rails g migration AddAmountToCarts 'amount:decimal{10,2}' user:references

# Creates a join table between `customers` and `products` tables.
bin/rails g migration CreateJoinTableCustomerProduct customer product
```

## Working with Tables

ActiveRecord provides a bunch of methods to create, update, and drop tables in the database. Let's explore the most common ones.

### Create Table

To create a new database table, use the&nbsp;[`create_table`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_table)&nbsp;method. This method accepts the name of the table and a block that's used to define the new table, e.g. to add columns, indexes, etc.

```ruby
# create_table(table_name, id: :primary_key, primary_key: nil, force: nil, **options)
create_table :subscribers do |t|
  t.string :name
  t.string :email
end
```

It creates a table named&nbsp;`subscribers`. Assumes an auto-incrementing, integer primary key named&nbsp;`id`.

> `t`&nbsp;is an instance of&nbsp;`ActiveRecord::ConnectionAdapters::TableDefinition`. It represents the database table schema and lets you manipulate the schema representation.

To create a join table, use the&nbsp;[`create_join_table`](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_join_table)&nbsp;method.

```ruby
# create join table between customers and products tables.
create_join_table :customers, :products
```

When creating the table, you may use any of the ActiveRecord's&nbsp;[column methods](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column)&nbsp;to define the table's columns.

**Options:**

- `:primary_key`&nbsp;- Change the primary key name. Default is&nbsp;`:id`
- `:force`&nbsp;- Drop the table if it already exists.&nbsp;**Warning: This will result in unwanted data loss, if the existing table has data.**
- `:if_not_exists`&nbsp;- If you try to create a table with duplicate name, Rails will throw an error. This option lets you return silently without raising an error, if the table already exists. Default is false.
- `:options`&nbsp;- Provide database-specific options.
- `:temporary`&nbsp;- Create a temporary table that will only exist during the current connection to the database.
- `id: false`&nbsp;- Do not generate a primary key at all.

**Column Options:**&nbsp;See the&nbsp;[Create Column](/rails-database-migrations-cheatsheet#create-column)&nbsp;section for available column options.

Here's a table that shows all available column types along with their corresponding values in different databases.

<table><tbody><tr><th class="lexxy-content__table-cell--header"><p><b><strong>Type</strong></b></p></th><th class="lexxy-content__table-cell--header"><p><b><strong>Description</strong></b></p></th><th class="lexxy-content__table-cell--header"><p><b><strong>MySQL</strong></b></p></th><th class="lexxy-content__table-cell--header"><p><b><strong>SQLite</strong></b></p></th><th class="lexxy-content__table-cell--header"><p><b><strong>PostgreSQL</strong></b></p></th></tr><tr><td><p>:integer</p></td><td><p>whole number</p></td><td><p>int(11)</p></td><td><p>integer</p></td><td><p>integer</p></td></tr><tr><td><p>:bigint</p></td><td><p>very large integer</p></td><td><p>bigint</p></td><td><p>integer</p></td><td><p>bigint</p></td></tr><tr><td><p>:float</p></td><td><p>floating point number</p></td><td><p>float</p></td><td><p>float</p></td><td><p>float</p></td></tr><tr><td><p>:decimal</p></td><td><p>financial calculations</p></td><td><p>decimal</p></td><td><p>decimal</p></td><td><p>decimal</p></td></tr><tr><td><p>:boolean</p></td><td><p>true or false</p></td><td><p>tinyint(1)</p></td><td><p>boolean</p></td><td><p>boolean</p></td></tr><tr><td><p>:string</p></td><td><p>255 characters</p></td><td><p>varchar(255)</p></td><td><p>varchar(255)</p></td><td><p>character varying(255)</p></td></tr><tr><td><p>:text</p></td><td><p>unlimited</p></td><td><p>text</p></td><td><p>text</p></td><td><p>text</p></td></tr><tr><td><p>:date</p></td><td><p>y, m, d (no time)</p></td><td><p>date</p></td><td><p>date</p></td><td><p>date</p></td></tr><tr><td><p>:time</p></td><td><p>h, m, s (no date)</p></td><td><p>time</p></td><td><p>time</p></td><td><p>time</p></td></tr><tr><td><p>:datetime</p></td><td><p>date and time</p></td><td><p>datetime</p></td><td><p>datetime</p></td><td><p>timestamp</p></td></tr><tr><td><p>:timestamp</p></td><td><p>same as datetime</p></td><td><p>datetime</p></td><td><p>datetime</p></td><td><p>timestamp</p></td></tr><tr><td><p>:json</p></td><td><p>JSON data</p></td><td><p>json</p></td><td><p>-</p></td><td><p>json</p></td></tr><tr><td><p>:binary</p></td><td><p>raw binary data</p></td><td><p>blob</p></td><td><p>blob</p></td><td><p>bytea</p></td></tr></tbody></table>

### Update Table

Use the&nbsp;[`change_table`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_table)&nbsp;method to update existing tables. Like&nbsp;`create_table`, the&nbsp;`change_table`&nbsp;method accepts the name of the table and a block to add columns or indexes to the table:

```ruby
change_table :products do |t|
  t.remove :description, :name
  t.string :service_number
  t.index :service_number
  t.rename :creator, :maker
end
```

### Rename Table

To rename an existing table, use the&nbsp;[`rename_table`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-rename_table)&nbsp;method. The following method renames the&nbsp;`from_table`&nbsp;to&nbsp;`to_table`.

```ruby
rename_table('from_table', 'to_table')
```

### Drop Table

To drop an existing table, you can use the&nbsp;[`drop_table`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-drop_table)&nbsp;method.

```ruby
drop_table('users')
```

Note:&nbsp;`drop_table`&nbsp;ignores the provided block and options when running the migration, but uses them when reverting the migration to generate the corresponding table.

```ruby
def change
  drop_table :accounts

  drop_table :posts do |t|
    t.string :title
    t.text :content
  end
end
```

## Referencing Other Tables

The naming convention for foreign keys is the singularized table name followed by&nbsp;`_id`.

For example, if table&nbsp;`projects`&nbsp;depends on table&nbsp;`clients`, i.e., a project&nbsp;`belongs_to`&nbsp;a client and a client&nbsp;`has_many`&nbsp;projects, then&nbsp;`projects`&nbsp;table will have a&nbsp;`client_id`&nbsp;column in it.

To add this foreign key, use the&nbsp;`add_reference :table_name, :reference`&nbsp;method. For example, if the&nbsp;`posts`&nbsp;table references a user, then&nbsp;`posts`&nbsp;will have a&nbsp;`user_id`&nbsp;column in it.

```ruby
def change
  # add a reference of user to posts.
  add_reference :posts, :user 
  # is same as
  add_belongs_to :posts, :user
end
```

Alternatively, you can use the&nbsp;`references`&nbsp;method on the&nbsp;`TableDefinition`&nbsp;instance yielded to&nbsp;`create_table`&nbsp;or&nbsp;`change_table`&nbsp;methods.

```ruby
change_table :posts do |t|
  t.references :user
  # or
  t.belongs_to :user
end
```

Note: Referencing another table will also create an index.

## Working with Columns

Similar to table, ActiveRecord provides various ways to work with columns. You can add new columns, modify existing ones, or delete them altogether. Let's explore the related methods.

### Create Column

As seen in the section on creating tables, you can specify new columns while creating a new table. But if you want to add new columns to an existing table, use the&nbsp;[`add_column`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column)&nbsp;method.

The&nbsp;`add_column(table_name, column_name, type)`&nbsp;method adds a new&nbsp;`type`&nbsp;column named&nbsp;`column_name`&nbsp;to&nbsp;`table_name`.

```ruby
# add_column(table_name, column_name, type, **options)

add_column(:users, :picture, :binary)
```

**Available Column Types**

The&nbsp;`type`&nbsp;parameter is normally one of the migrations native types, which is one of the following:&nbsp;`:primary_key`,&nbsp;`:string`,&nbsp;`:text`,&nbsp;`:integer`,&nbsp;`:bigint`,&nbsp;`:float`,&nbsp;`:decimal`,&nbsp;`:numeric`,&nbsp;`:datetime`,&nbsp;`:time`,&nbsp;`:date`,&nbsp;`:binary`,&nbsp;`:blob`,&nbsp;`:boolean`.

**Column Options**

- `:default`&nbsp;- sets the default value. If you don't set it, it will be&nbsp;`NULL`.
- `limit: size`&nbsp;- adds a limit for the column. For string types, it's number of characters. For others, it specifies the number of bytes.
- `null: false`&nbsp;- adds a \`not null\` constraint.
- `precision: 10`&nbsp;- specifies the precision (total # of digits) for&nbsp;`:decimal`,&nbsp;`:numeric`,&nbsp;`:datetime`&nbsp;and&nbsp;`:time`&nbsp;columns.
- `scale: 3`&nbsp;- specifies the number of digits to the right of the decimal point for&nbsp;`:decimal`&nbsp;and&nbsp;`:numeric`&nbsp;columns.
- `if_not_exists: true`&nbsp;- do not add the column if it already exists (to avoid duplication error)
- `comment: text`&nbsp;- adds a comment that will be added to&nbsp;`schema.rb`.

Note: The same options apply while&nbsp;[crating a new table](/rails-database-migrations-cheatsheet#create-table)&nbsp;with new columns.

### Update Column

The&nbsp;[`change_column`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column)&nbsp;method allows you to modify the type and attributes of existing columns. For example, to increase the size of a&nbsp;`name`&nbsp;column, use the&nbsp;`change_column`&nbsp;method as follows:

```ruby
# change_column(table_name, column_name, type, **options)

change_column :users, :name, :string, limit: 80
```

### Rename Column

To rename a column, use the&nbsp;[`rename_column`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-rename_column)&nbsp;method.

```ruby
# rename_column(table_name, column_name, new_column_name)

rename_column(:suppliers, :description, :name)
```

Renames the column from&nbsp;`description`&nbsp;to&nbsp;`name`&nbsp;on the&nbsp;`suppliers`&nbsp;table

### Drop Column

Finally, to drop a column, you may use the&nbsp;[`remove_column`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_column)&nbsp;method.

```ruby
remove_column :users, :password
```

Alternatively, you can also call the&nbsp;`rename_column`&nbsp;and the&nbsp;`remove_column`&nbsp;method on the table definition, while changing a table.

```ruby
change_table :users do |t|
  t.remove_column :password
end
```

If you want to drop multiple columns from a table, pass the list of column names to the&nbsp;[`remove_columns`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_columns)&nbsp;method.

```ruby
remove_columns :users, :password, :address, :phone
```

## Working with Indexes (Indices)

Database indexes provide a way to quickly lookup the requested data. An index is a powerful data structure that makes your database queries faster.

The database uses these indices to search for data without looping through every row in the table. The indices are updated automatically whenever new data is added or removed.

### Create Index

ActiveRecord supports several types of indexes. Use the&nbsp;`add_index`&nbsp;or&nbsp;`t.index`&nbsp;method to add new index. Additionally, you can mark the index as unique or give it a different name.

The following example creates a new&nbsp;`email`&nbsp;column and specifies that its values should be unique.

```ruby
create_table :users do |t|
  t.string :name, index: true
  t.string :email, index: { unique: true }
  t.index [:title, :address], unique: true
end
```

Alternatively, you may use the&nbsp;[`add_index`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index)&nbsp;method.

```ruby
def change
  # adds a new index on the `posts` table for the `title` column. 
  add_index :posts, :title

  # adds a new index for the `company_id` and `manager_id` columns;
  add_index :suppliers, [:company_id, :manager_id]
end
```

You may even pass an array of columns to the&nbsp;`add_index`&nbsp;method to create a compound (or composite) index:

```ruby
add_index(:accounts, [:branch_id, :party_id], unique: true)
```

When creating an index, ActiveRecord will automatically generate an index name based on the table, column names, and the index type, but you may pass a second argument to the method to specify the index name yourself.

```ruby
create_table :users do |t|
  t.string :name, index: true
  t.string :email, index: { unique: true, name: 'unique_emails' }
end
  
 # OR
  
add_index(:accounts, [:branch_id, :party_id], unique: true, name: 'by_branch_party')
```

### Rename Index

To rename an index, use the&nbsp;[`rename_index`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-rename_index)&nbsp;method. This method accepts the table name as its first argument and the current index name and the desired name as its second and third arguments, respectively.

```ruby
rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name'
```

Alternatively, use the&nbsp;`rename_index`&nbsp;method while changing a table. This is useful when you want to change multiple index names in a single migration.

```ruby
change_table :users do |t|
  t.rename_index(:user_id, :account_id)
end
```

### Drop Index

To drop an index, you may use the&nbsp;[`remove_index`](https://api.rubyonrails.org/v7.0.7/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_index)&nbsp;method, passing the name of the table and either the column name or the name of the index.

```ruby
remove_index :accounts, :branch_id

remove_index :accounts, column: [:branch_id, :party_id]

remove_index :accounts, name: :by_branch_party
```

Alternatively, use the&nbsp;`remove_index`&nbsp;method while changing the table.

```ruby
t.remove_index(:branch_id)
t.remove_index(column: [:branch_id, :party_id])
t.remove_index(name: :by_branch_party)
t.remove_index(:branch_id, name: :by_branch_party)
```

**I'll stop here.**&nbsp;If you think this cheatsheet should include any other operations, methods, or options, please let me know in the comments below.

