Exception: ActiveRecord::IrreversibleMigration

Inherits:
MigrationError show all
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 ActiveRecord::IrreversibleMigration error.

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

  execute "    ALTER TABLE distributors\n      ADD CONSTRAINT zipchk\n        CHECK (char_length(zipcode) = 5) NO INHERIT;\n  SQL\nend\nend\n"

There are two ways to mitigate this problem.

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

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

 execute "   ALTER TABLE distributors\n     ADD CONSTRAINT zipchk\n       CHECK (char_length(zipcode) = 5) NO INHERIT;\n SQL\nend\n\ndef down\n execute <<~SQL\n   ALTER TABLE distributors\n     DROP CONSTRAINT zipchk\n SQL\n\n drop_table :distributors\nend\n"

end

  1. Use the #reversible method in #change method:

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

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

Method Summary

Methods inherited from MigrationError

#initialize

Constructor Details

This class inherits a constructor from ActiveRecord::MigrationError