Migrations and Rollbacks
In Rails applications, for database related changes like creating a table, adding a column, removing a column, etc. we write a lot of migrations.
To run those migrations, we use the db:migrate
command.
> rails db:migrate
But sometimes, while writing migrations we might end up making some mistakes.
To revert such mistakes we use db:rollback
,
which restores the database to a state,
before the latest migration was run.
> rails db:rollback
We can also pass STEP
as an environment variable to this command,
to specify the number of migrations to revert.
For example, if we have to revert latest 3 migrations
then we’ll run the following command.
> rails db:rollback STEP=3
Multiple databases
Rails 6 has added support for multiple databases.
Thus we will have multiple directories similar to migrate
under db
folder.
We can pass an additional db
option while creating the new migration
and this will add that migration under a particular database’s migrate directory.
> rails g migration AddUser first_name:string last_name:string --db=secondary
We can run all database migrations in one go by running the following command.
> rails db:migrate
If we want to run migrations of the specific database then we can run the following command.
> rails db:migrate:secondary
Here secondary
is the name of the database.
Now if we want to revert the latest migration then we can run the following command.
> rails db:rollback
Since we didn’t have a way to specify which database we really want to rollback the migration from, it always ended up reverting the latest migration of the primary database.
To fix this issue,
Rails 6.0.2.1 has added
support for database name in the db:rollback
command
similar to db:migrate
.
> rails db:rollback:[NAME]
Now, if we run db:rollback
command without name
for multiple database applications
then it throws the following error.
> rails db:rollback
rails aborted!
You're using a multiple database application. To use `db:rollback` you must run the namespaced task with a VERSION. Available tasks are db:rollback:primary and db:rollback:secondary.
To fix this, we will need to run the following command.
> rails db:rollback:secondary
The above command will revert the latest migration of the secondary
database.