How to Safely Update Rails Migrations in a Docker Environment

In Rails development, you may occasionally need to change the data type of a column after running migrations.

This article explains how to safely alter table structures in a Rails application within a Docker environment. We’ll demonstrate this by changing the price column in a Books table from string to integer.


Initial Table Structure

Consider the following migration has already been executed:

class CreateBooks < ActiveRecord::Migration[7.1]
  def change
    create_table :books do |t|
      t.string :price

      t.timestamps
    end
  end
end

However, you might later realize you need numerical handling for price values.


Recommended Approach (Creating a New Migration)

Rails recommends adding a new migration instead of directly modifying existing ones.

Step 1: Generate a new migration file in Docker

In Docker environments, Rails commands should be run inside the container:

docker compose exec web bundle exec rails generate migration ChangeBooksPriceToInteger

This creates a new migration file:

db/migrate/20250314000000_change_books_price_to_integer.rb

Step 2: Edit the migration file

Open the generated migration file and define the type change clearly:

class ChangeBooksPriceToInteger < ActiveRecord::Migration[7.1]
  def up
    change_column :books, :price, :integer
  end

  def down
    change_column :books, :price, :string
  end
end
  • up method: Defines changes applied when running migrations.
  • down method: Defines changes applied during rollbacks.

Step 3: Run the migration in Docker

Apply the changes to the database:

docker compose exec web bundle exec rails db:migrate

Now, the price column of the Books table has been updated to the integer type.


Important Notes

  • Always verify that changing column types won't cause data inconsistency in environments with existing data, especially in production.
  • For non-critical data in development environments, rolling back and re-running the initial migration is possible, but adding a new migration is safer for production systems.

Summary

  • In Docker environments, always run Rails migration commands inside the container.
  • Safely change Rails migrations by adding new migration files rather than altering existing ones.
  • Clearly define changes and rollbacks using up and down methods.

This summarizes how to safely update existing Rails migrations in a Docker environment.

References

Active Record Migrations