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
1. What Are Migrations in Ruby on Rails?
2. How does Rails keep track of migrations?
3. What is difference between model and migration in Rails?
4. How to create a Migration in Ruby on Rails
5. How to define a migration in Ruby on Rails
6. Running Migrations in Ruby on Rails
7. Rolling Back Migrations in Ruby on Rails
8. Managing Schema Changes in Ruby on Rails
8. Best Practices for Migrations
8. Conclusion
9. 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:
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:
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 fromActiveRecord::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 beActiveRecord::Migration[5.2]
. -
create_table
creates a new table namedusers
. -
t.string :name
andt.string :email
addname
andemail
columns of typestring
. -
t.timestamps
addscreated_at
andupdated_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:
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:
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:
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:
- 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.
- Test Migrations: Always test your migrations in a development environment before applying them to production. This helps catch any errors or unintended side effects.
-
Use Descriptive Names: Use descriptive names for your migration files to make it clear what changes they contain. For example,
AddEmailToUsers
is more descriptive thanUpdateUsers
. - 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.
- 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?
Dissecting Rails Migrations
What is difference between model and migration in Rails?
Discover more from Coursity
Subscribe to get the latest posts sent to your email.