How to Rename a Column Using Migration in Ruby on Rails
In Ruby on Rails, you rename a column using a migration by calling
rename_column :table_name, :old_column, :new_column. This command changes the column name in the database schema safely and can be run with rails db:migrate.Syntax
The rename_column method takes three arguments:
- table_name: The name of the table containing the column.
- old_column: The current name of the column you want to rename.
- new_column: The new name you want to give to the column.
This method is used inside a migration class in the change method.
ruby
class RenameOldColumnToNewColumn < ActiveRecord::Migration[7.0] def change rename_column :table_name, :old_column, :new_column end end
Example
This example renames the column username to login in the users table. After running the migration, the database schema will reflect the new column name.
ruby
class RenameUsernameToLoginInUsers < ActiveRecord::Migration[7.0] def change rename_column :users, :username, :login end end
Output
== 20240601000000 RenameUsernameToLoginInUsers: migrating ======================
-- rename_column(:users, :username, :login)
-> 0.0012s
== 20240601000000 RenameUsernameToLoginInUsers: migrated (0.0013s) ==========
Common Pitfalls
- Trying to rename a column that does not exist will cause an error.
- Renaming a column without updating your Rails models or code that uses the old column name will cause bugs.
- Do not rename columns in production without ensuring all code and queries are updated.
Always check your schema and test your app after renaming.
ruby
class WrongRename < ActiveRecord::Migration[7.0] def change # This will fail if :old_name does not exist rename_column :users, :old_name, :new_name end end # Correct approach: class CorrectRename < ActiveRecord::Migration[7.0] def change rename_column :users, :existing_column, :new_column end end
Quick Reference
Use this cheat sheet to rename columns safely:
| Action | Command Example | Notes |
|---|---|---|
| Rename column | rename_column :table, :old_col, :new_col | Inside migration change method |
| Run migration | rails db:migrate | Applies the rename to the database |
| Rollback migration | rails db:rollback | Reverts the rename if needed |
| Check schema | cat db/schema.rb | Verify column name changed |
Key Takeaways
Use rename_column inside a migration's change method to rename columns safely.
Always specify the table name, old column name, and new column name correctly.
Run rails db:migrate to apply the rename to your database.
Update your Rails code to use the new column name after renaming.
Test your app thoroughly after renaming columns to avoid bugs.