# A Deep Dive Into Database Migrations in Rails

*Published on September 09, 2022*

---


Like source code, database schema changes and evolves over time. Migrations are a feature of Active Record that allows you to manage the database schema changes gracefully, without writing any SQL. This post contains my notes on Active Record migrations from the official&nbsp;[Rails guides](https://guides.rubyonrails.org/active_record_migrations.html).

### Key Points

- Think of each migration as a new version of the database.
- Migrations allow you to modify schema in a database-independent way.
- `db/schema.rb`&nbsp;file contains the current structure of your database.

Here’s an example of a migration that adds a&nbsp;`time_logs`&nbsp;table with four explicit columns named&nbsp;`project`,&nbsp;`task`,&nbsp;`start_time`, and&nbsp;`end_time`. As you can see, it’s a Ruby class with a change method. Along with the four columns, the migration will also add an id column as a primary key. The timestamps macro adds two columns&nbsp;`created_at`&nbsp;and&nbsp;`updated_at`.

```ruby
class CreateTimeLogs < ActiveRecord::Migration[6.1]
  def change
    create_table :time_logs do |t|
      t.string :project
      t.string :task
      t.datetime :start_time
      t.datetime :end_time

      t.timestamps
    end
  end
end
```

To generate a migration, run the following command, which generates an empty migration.

```bash
bin/rails generate migration AddPartNumberToProducts
```

It generates the following code:

```ruby
class AddPartNumberToProducts < ActiveRecord::Migration[6.0]
  def change
  end
end
```

If you want to add/remove columns or index to a table, use the&nbsp;`add_column`,&nbsp;`remove_column`, and&nbsp;`add_index`&nbsp;methods.

```ruby
class AddPartNumberToProducts < ActiveRecord::Migration[6.0]
  def change
    add_column :products, :part_number, :string
    add_index :products, :part_number
  end
end
```

Rails even allows you to mention the changes in the command.

```bash
bin/rails generate migration CreateProducts name:string part_number: string
# or
bin/rails generate migration AddDetailsToProducts part_number:string price:decimal
```

### Naming Conventions

If the name of the migration starts with&nbsp;`Create__`&nbsp;followed by column names along with the types, then the resulting migration will create a table.

```ruby
# bin/rails generate migration CreateProducts name:string part_number:string

class CreateProducts < ActiveRecord::Migration[6.0]
  def change
    create_table :products do |t|
      t.string :name
      t.string :part_number

      t.timestamps
    end
  end
end
```

If the name starts with&nbsp;`Add`, it will add columns to an existing table.

```ruby
# bin/rails generate migration AddDetailsToProducts part_number:string price:decimal

class AddDetailsToProducts < ActiveRecord::Migration[6.0]
  def change
    add_column :products, :part_number, :string
    add_column :products, :price, :decimal
  end
end
```

If the name contains&nbsp;`JoinTable`, the generator will produce a join table.

```ruby
# bin/rails generate migration CreateJoinTableCustomerProduct customer product

class CreateJoinTableCustomerProduct < ActiveRecord::Migration[6.0]
  def change
    create_join_table :customers, :products do |t|
      # t.index [:customer_id, :product_id]
      # t.index [:product_id, :customer_id]
    end
  end
end
```

### Model Generation

If you would like to generate a model class along with the migration, use the model generator.

```bash
➜  rails generate model Post title:string content:text

Running via Spring preloader in process 71862
      invoke  active_record
      create    db/migrate/20210722065837_create_posts.rb
      create    app/models/post.rb
      invoke    test_unit
      create      test/models/post_test.rb
      create      test/fixtures/posts.yml
```

This generates the following code.

```ruby
# xxxx_create_posts.rb
class CreatePosts < ActiveRecord::Migration[6.1]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :content

      t.timestamps
    end
  end
end

# post.rb
class Post < ApplicationRecord
end
```

## Rails Migration Commands

So far, we have seen how to generate migrations in Rails. However, creating a migration on its own doesn’t update the database. You have to run the migration to make the changes. This post summarizes all the commands that modify the database.

`rails db:migrate`

You will be using this command often to run the migration. This command runs the&nbsp;`change`&nbsp;method for all the migrations that have not run yet, in the order based on migration’s date. It also updates the&nbsp;`db/schema.rb`&nbsp;file to match the database structure.

`rails db:rollback`

Reverts the last migration. If you made a mistake and want to go back to the state before running the migration, use this command. Provide the&nbsp;`STEP=n`&nbsp;option if you want to revert last&nbsp;`n`&nbsp;migrations. You can run&nbsp;`db:migrate`&nbsp;after making corrections to the migration.

However, the Rails guides recommend that it’s not a good idea to edit an existing migration, especially if it has already been run on a production database. What you should do is create a new migration that performs the changes you need.

`rails db:setup`

This command creates the database, loads the schema, and initializes it with the seed data.

`rails db:reset`

Drop the database and set it up again. Equivalent to running&nbsp;`db:drop`&nbsp;and&nbsp;`db:setup`&nbsp;in sequence.

`rails db:seed`

Migrations can also add, modify, or delete data in the database. However, to add seed data after a database is created, you can use the ‘seeds’ feature in the database. Simply add some sample data in&nbsp;`db/seeds.rb`, and run the&nbsp;`db:seed`&nbsp;command.

`rails db:prepare`

This command creates the database if it doesn't exist, then runs the migrations to update the database schema. Finally, it runs the&nbsp;`db:seed`&nbsp;command to seed the database.

### Schema Files

Rails stores the current structure of the database schema in the&nbsp;`db/schema.rb`&nbsp;file. Schema files are also handy to check the attributes of a model. This information is not in the model’s code and is frequently spread across several migrations, but it’s outlined in the schema file.

Schema files are commonly used to create new databases, and it’s recommended to check them into source control.

By default, the schema file uses the&nbsp;`:ruby`&nbsp;format, but you can set it to&nbsp;`:sql`. This will save the schema in&nbsp;`db/structure.sql`&nbsp;file, using a database-specific tool, e.g.&nbsp;`pg_dump`&nbsp;for PostgreSQL and&nbsp;`SHOW CREATE TABLE`&nbsp;for MySQL.

`rails db:schema:load`

To create a new instance of your database, you can simply run the&nbsp;`rails db:schema:load`&nbsp;command. It’s better than running the entire migration history, as it may fail to apply correctly.

The&nbsp;`:ruby`&nbsp;format cannot express everything in the database schema, such as triggers, stored procedures, etc. Setting the format to&nbsp;`:sql`&nbsp;will ensure that an accurate schema is generated and a perfect copy of the database schema is created upon running&nbsp;`db:schema:load`.

The&nbsp;`db/schema.rb`&nbsp;or&nbsp;`db/structure.sql`&nbsp;is a snapshot of the current state of your database and is the authoritative source for rebuilding that database. This allows you to delete old migration files.

