Exception: ActiveRecord::IrreversibleMigration
| Relationships & Source Files | |
| Super Chains via Extension / Inclusion / Inheritance | |
| Class Chain: 
          self,
           ActiveRecordError,
          StandardError | |
| Instance Chain: 
          self,
           ActiveRecordError,
          StandardError | |
| Inherits: | ActiveRecord::MigrationError 
 | 
| Defined in: | activerecord/lib/active_record/migration.rb | 
Overview
::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 IrreversibleMigration error.
class IrreversibleMigrationExample < ActiveRecord::Migration[7.2]
  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
endThere are two ways to mitigate this problem.
- 
Define #upand#downmethods instead of#change:
class ReversibleMigrationExample < ActiveRecord::Migration[7.2]
  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- 
Use the #reversiblemethod in#changemethod:
class ReversibleMigrationExample < ActiveRecord::Migration[7.2]
  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