A quick guide on Migrations in Ruby on Rails for beginners
Tags: rails, ruby, codenewbie, beginners
Published: 2024-07-04 13:43:43

Ruby on Rails (RoR), often simply referred to as Rails, is a popular web application framework written in Ruby. It is known for its simplicity, convention over configuration, and rapid development capabilities. One of the key features that make Rails a powerful tool for web developers is its handling of database migrations.

## Table of Contents
&nbsp;1. [What Are Migrations in Ruby on Rails?](#what-are-migrations-in-ruby-on-rails)
&nbsp;2. [How does Rails keep track of migrations?](#how-does-rails-keep-track-of-migrations)
&nbsp;3. [What is difference between model and migration in Rails?](#what-is-difference-between-model-and-migration-in-rails)
&nbsp;4. [How to create a Migration in Ruby on Rails](#how-to-create-a-migration-in-ruby-on-rails)
&nbsp;5. [How to define a migration in Ruby on Rails](#how-to-define-a-migration-in-ruby-on-rails)
&nbsp;6. [Running Migrations in Ruby on Rails](#running-migrations-in-ruby-on-rails)
&nbsp;7. [Rolling Back Migrations in Ruby on Rails](#rolling-back-migrations-in-ruby-on-rails)
&nbsp;8. [Managing Schema Changes in Ruby on Rails](#managing-schema-changes-in-ruby-on-rails)
&nbsp;8. [Best Practices for Migrations](#best-practices-for-migrations)
&nbsp;8. [Conclusion](#conclusion)
&nbsp;9. [References](#references) 

## What Are Migrations in Ruby on Rails?
Migrations in Ruby on Rails are a way to manage database schema changes over time. They allow developers to evolve the database schema as the application grows and requirements change. With migrations, you can add, remove, or modify tables and columns in a systematic and version-controlled manner. Migrations provide a structured way to track and apply these changes, ensuring consistency across different development environments.

##How does Rails keep track of migrations?
Migrations are stored as files in the db/migrate directory, one for each migration class. The name of the file is of the form `YYYYMMDDHHMMSS_create_products. rb`, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration.

##What is difference between model and migration in Rails?
Rails Model (Active Record) works with **SQL**, and Rails Migration works with **DDL**. Rails Model supports ways to interact with the database, while Rails Migration changes the database structure. A migration can change the name of a column in a `books` table. A migration can remove the table `book_covers`.

## How to create a Migration in Ruby on Rails
To create a new migration in a Rails application, you can use the Rails generator command. This command generates a new migration file with a timestamp in its filename to ensure uniqueness and chronological ordering. Here's how you can create a migration to add a new table:

```bash
rails generate migration CreateUsers
```

This command creates a migration file in the `db/migrate` directory with a name like `20230703094523_create_users.rb`. The generated file contains an empty `change` method where you define the changes to the database schema.

## How to define a migration in Ruby on Rails
Once you have created a migration, you must define the changes you want to make. Rails provides several methods to manipulate the database schema within the `change` method. For example, to create a `users` table with some basic columns, you would modify the migration file as follows:

```ruby
class CreateUsers < ActiveRecord::Migration[6.1]
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.timestamps
    end
  end
end
```

In this example:
- The migration contains a class `CreateUsers` that inherits from `ActiveRecord::Migration[6.1]`. As I'm using Rails 6.1, the migration superclass has [6.1]. If I was using Rails 5.2, then the superclass would be `ActiveRecord::Migration[5.2]`.
- `create_table` creates a new table named `users`.
- `t.string :name` and `t.string :email` add `name` and `email` columns of type `string`.
- `t.timestamps` adds `created_at` and `updated_at` columns, which are automatically managed by Rails.

## Running Migrations in Ruby on Rails
After defining your migration, you need to run it to apply the changes to the database. You can do this using the following command:

```bash
rails db:migrate
```

This command runs all pending migrations in the `db/migrate` directory, applying the changes defined in each migration file to the database. Rails keeps track of which migrations have been applied using a special `schema_migrations` table, ensuring that each migration is only run once.

## Rolling Back Migrations in Ruby on Rails
Sometimes, you may need to undo a migration if you made a mistake or need to revert to a previous state. Rails allows you to roll back migrations using the following command:

```bash
rails db:rollback
```

This command rolls back the most recent migration. If you need to roll back multiple migrations, you can specify the number of steps:

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

Rolling back a migration reverses the changes made in the `change` method. For more complex changes, such as renaming a column, you may need to define `up` and `down` methods instead of a single `change` method to specify how to apply and undo the migration.

## Managing Schema Changes in Ruby on Rails
As your application grows, you will likely need to make many changes to your database schema. Rails migrations provide a systematic way to manage these changes, ensuring that your development, testing, and production environments stay in sync. By keeping track of schema changes in version-controlled migration files, you can collaborate with other developers more effectively and deploy updates with confidence.

## Best Practices for Migrations
Here are some best practices to keep in mind when working with Rails migrations:
1. **Keep Migrations Simple**: Each migration should focus on a single change to the database schema. This makes it easier to understand and manage the changes.
2. **Test Migrations**: Always test your migrations in a development environment before applying them to production. This helps catch any errors or unintended side effects.
3. **Use Descriptive Names**: Use descriptive names for your migration files to make it clear what changes they contain. For example, `AddEmailToUsers` is more descriptive than `UpdateUsers`.
4. **Backup Your Database**: Before running migrations in a production environment, ensure you have a backup of your database. This provides a safety net in case something goes wrong.
5. **Version Control**: Keep your migration files under version control to track changes and collaborate with other developers.

## Conclusion
Migrations are a powerful feature of Ruby on Rails that allow you to manage database schema changes in a systematic and version-controlled manner. By understanding how to create, define, run, and rollback migrations, you can keep your database schema in sync with your application's evolving requirements. Following best practices for migrations will help you maintain a clean and manageable codebase, ensuring that your Rails application remains robust and scalable.

##References
[How do Rails keep track of migrations?](https://guides.rubyonrails.org/v3.2/migrations.html#:~:text=Migrations%20are%20stored%20as%20files,the%20name%20of%20the%20migration)
[Dissecting Rails Migrations](https://blog.appsignal.com/2020/04/14/dissecting-rails-migrationsl.html)
[What is difference between model and migration in Rails?](https://www.codementor.io/@duykhoa12t/rails-migration-overview-17ouwntenm#:~:text=Rails%20Model%20(Active%20Record)%20works,can%20remove%20the%20table%20book_covers%20)