This tutorial aims to guide you through the process of handling migrations and managing your database schema in Rails. By the end of this tutorial, you should be able to understand and use Rails migrations to create, modify, and manage different versions of your database schema effectively.
You will learn:
- What Rails Migrations are and why they're important.
- How to create, modify and rollback migrations.
- Managing your database schema using Rails Migrations.
Prerequisites:
- Basic knowledge of Ruby on Rails.
- A Rails application set up on your local machine.
Rails migrations are a convenient way to alter your database schema over time in a consistent and easy way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent.
Creating a Migration:
Migrations are typically created with the rails generate
command followed by migration
and the name of your migration.
rails generate migration AddPartNumberToProducts part_number:string
This will create a migration file in the db/migrate
directory.
Running Migrations:
To apply the changes defined in the migration file to your database, you run the migrations using the rails db:migrate
command.
Rolling Back Migrations:
Migrations can also be rolled back using the rails db:rollback
command, which will undo the last migration command.
Example 1: Creating a Migration
class AddPartNumberToProducts < ActiveRecord::Migration[6.0]
def change
add_column :products, :part_number, :string
end
end
This migration adds a new column, part_number
, to the products
table.
Example 2: Modifying a Migration
class ChangePartNumberFormatInProducts < ActiveRecord::Migration[6.0]
def up
change_column :products, :part_number, :integer
end
def down
change_column :products, :part_number, :string
end
end
This migration changes the type of the part_number
column from string
to integer
.
In this tutorial, we've covered how to create, modify, and manage your database schema using Rails migrations. We've also learned how to roll back changes and why migrations are essential for database schema management.
Create a migration to add a reviews
table with content
(text), user_id
(integer), and product_id
(integer).
Modify the reviews
table to change the content
column into a string
type.
Roll back the last migration you applied.