How to Use change Method in Rails Migration for Database Changes
In Ruby on Rails migrations, the
change method defines reversible database changes like adding or removing columns. Rails automatically knows how to reverse these changes when rolling back, making change the preferred method for simple migrations.Syntax
The change method is defined inside a migration class and contains the database schema changes you want to apply. Rails uses this method to apply and reverse changes automatically.
def change: Starts the method where you write your migration code.- Migration commands like
add_column,remove_column,rename_column,create_table, etc. end: Ends the method.
ruby
class ExampleMigration < ActiveRecord::Migration[7.0] def change add_column :users, :age, :integer end end
Example
This example adds a new column age of type integer to the users table. When you run rails db:migrate, the column is added. If you run rails db:rollback, Rails automatically removes the column because the change method is reversible.
ruby
class AddAgeToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :age, :integer end end
Output
Migration adds 'age' column to 'users' table on migrate; removes it on rollback.
Common Pitfalls
Some migration commands are not reversible automatically, causing errors on rollback. For example, execute with raw SQL or rename_column in older Rails versions may not reverse automatically.
To fix this, use def up and def down methods instead of change for complex changes, or provide reversible blocks inside change.
ruby
class RenameUsernameInUsers < ActiveRecord::Migration[7.0] def change # This may not be reversible automatically rename_column :users, :username, :login end end # Correct approach with reversible block: class RenameUsernameInUsers < ActiveRecord::Migration[7.0] def change reversible do |dir| dir.up { rename_column :users, :username, :login } dir.down { rename_column :users, :login, :username } end end end
Quick Reference
| Command | Description | Reversible Automatically? |
|---|---|---|
| add_column | Adds a new column to a table | Yes |
| remove_column | Removes a column from a table | No (requires manual down or reversible block) |
| rename_column | Renames a column | No (use reversible block) |
| create_table | Creates a new table | Yes |
| drop_table | Drops a table | No (use reversible block) |
| execute | Runs raw SQL | No (use reversible block) |
Key Takeaways
Use the change method in migrations for simple reversible database changes.
Rails automatically knows how to reverse many common migration commands inside change.
For complex or non-reversible commands, use reversible blocks or separate up/down methods.
Always test rollback with rails db:rollback to ensure reversibility.
Use ActiveRecord migration commands instead of raw SQL for better reversibility.