Solution 1: Undo Last Migration
If it is a simple typo in the last migration, use the db:rollback
command to undo the last change. Then open the previous migration file, fix your typo, and rerun the migration. Make sure that no new data is inserted in the table or that no one on your team runs the stale migration.
$ bin/rails db:rollback
# make your changes
$ bin/rails db:migrate
Only edit a migration if you just created it, realize it's wrong, no related data is inserted in the database, and no one on your team has run it yet.
Solution 2: Rename a Column with a New Migration
If the column is already populated with data or it is live in production, use a database migration. Rails migrations are the best way to update and evolve the database schema over time, including column names.
Step One: Generate a Migration
Create a new migration using the Rails generator as follows:
> bin/rails generate migration RenameBodyToContent
This command will create a new empty migration file in the db/migrate
directory.
class RenameBodyToContent < ActiveRecord::Migration[7.1]
def change
end
end
Step Two: Update the Column Name
The rename_column
method renames a database column.
rename_column(table_name, column_name, new_column_name)
If you want to change the column name from body
to content
in a table named posts
call the above method as follows:
class RenameBodyToContent < ActiveRecord::Migration[7.1]
def change
rename_column :posts, :body, :content
end
end
Step Three: Run the Migration
To run the above migration, use the db:migrate
command. It executes the change
method which will run the rename_column
method to update the column name. Running a migration will also update your db/schema.rb
file to match the structure of your database.
> bin/rails db:migrate
That's it. Your database table should now have the new column name.
Finally, change all the places in the codebase where you were referencing the old column names with the new column name. Run the tests, and make sure they still pass.
Solution 3: Renaming Multiple Columns
If you want to update multiple column names, typing the table name can be tedious. To avoid having to type the table name repeatedly, use the change_table
method, which takes a block for changing columns in a table.
# change_table() yields a Table instance
change_table(:suppliers) do |t|
t.rename(:body, :content)
t.rename(:author, :publisher)
# other column transformations
end
Check the Table
class for all available column transformations.