class IrreversibleMigration

Ruby on Rails 7.1.6

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Exception that can be raised to stop migrations from being rolled back. For example the following migration is not reversible. Rolling back this migration will raise an ActiveRecord::IrreversibleMigration error.

class IrreversibleMigrationExample < ActiveRecord::Migration[7.1]
  def change
    create_table :distributors do |t|
      t.string :zipcode
    end

    execute <<~SQL
      ALTER TABLE distributors
        ADD CONSTRAINT zipchk
          CHECK (char_length(zipcode) = 5) NO INHERIT;
    SQL
  end
end

There are two ways to mitigate this problem.

  1. Define #up and #down methods instead of #change:

class ReversibleMigrationExample < ActiveRecord::Migration[7.1]
  def up
    create_table :distributors do |t|
      t.string :zipcode
    end

    execute <<~SQL
      ALTER TABLE distributors
        ADD CONSTRAINT zipchk
          CHECK (char_length(zipcode) = 5) NO INHERIT;
    SQL
  end

  def down
    execute <<~SQL
      ALTER TABLE distributors
        DROP CONSTRAINT zipchk
    SQL

    drop_table :distributors
  end
end
  1. Use the #reversible method in #change method:

class ReversibleMigrationExample < ActiveRecord::Migration[7.1]
  def change
    create_table :distributors do |t|
      t.string :zipcode
    end

    reversible do |dir|
      dir.up do
        execute <<~SQL
          ALTER TABLE distributors
            ADD CONSTRAINT zipchk
              CHECK (char_length(zipcode) = 5) NO INHERIT;
        SQL
      end

      dir.down do
        execute <<~SQL
          ALTER TABLE distributors
            DROP CONSTRAINT zipchk
        SQL
      end
    end
  end
end

Inherits from

ActiveRecord::MigrationError

Type at least 2 characters to search.

↑↓ navigate · open · esc close