How to Use Up and Down Methods in Ruby on Rails Migrations
In Ruby on Rails migrations, you use the
up method to define changes to apply to the database and the down method to define how to reverse those changes. This approach gives you full control over applying and rolling back migrations manually.Syntax
The up method contains code to apply the migration, like creating or modifying tables. The down method contains code to undo those changes, like dropping tables or columns. Rails runs up when migrating forward and down when rolling back.
ruby
class ExampleMigration < ActiveRecord::Migration[7.0] def up create_table :examples do |t| t.string :name t.timestamps end end def down drop_table :examples end end
Example
This example shows a migration that creates a products table in the up method and drops it in the down method. Running rails db:migrate applies the up method, and rails db:rollback runs the down method.
ruby
class CreateProducts < ActiveRecord::Migration[7.0] def up create_table :products do |t| t.string :title t.decimal :price, precision: 8, scale: 2 t.timestamps end end def down drop_table :products end end
Output
== 20240601000000 CreateProducts: migrating ================================
-- create_table(:products)
-> 0.0020s
== 20240601000000 CreateProducts: migrated (0.0021s) ===============================
== 20240601000000 CreateProducts: reverting ==================================
-- drop_table(:products)
-> 0.0015s
== 20240601000000 CreateProducts: reverted (0.0016s) =================================
Common Pitfalls
- Forgetting to define the
downmethod causes rollback errors. - Writing irreversible changes in
upwithout a matchingdownmakes rollback impossible. - Using both
changeandup/downmethods in the same migration causes conflicts.
ruby
class WrongMigration < ActiveRecord::Migration[7.0] def up add_column :users, :age, :integer end # Missing down method causes rollback failure end # Correct way: class FixedMigration < ActiveRecord::Migration[7.0] def up add_column :users, :age, :integer end def down remove_column :users, :age end end
Quick Reference
| Method | Purpose | When It Runs |
|---|---|---|
| up | Apply migration changes | When running rails db:migrate |
| down | Revert migration changes | When running rails db:rollback |
| change | Auto reversible migration | When running migrate or rollback (if reversible) |
Key Takeaways
Use the up method to define how to apply database changes in a migration.
Use the down method to define how to reverse those changes for rollback.
Always provide both up and down methods for safe migration and rollback.
Avoid mixing change method with up/down methods in the same migration.
Test migrations by running migrate and rollback commands to ensure reversibility.