跳至內容 跳至搜尋

Exception,可用來停止 migrations 還原。例如,以下 migrations 是無法還原的。還原此 migrations 會產生一則 ActiveRecord::IrreversibleMigration 錯誤。

class IrreversibleMigrationExample < ActiveRecord::Migration[8.0]
  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

有兩種方法可以減輕這個問題。

  1. 定義 #up#down 方法,而不是 #change

class ReversibleMigrationExample < ActiveRecord::Migration[8.0]
  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. 使用 #change 方法中的 reversible 方法

class ReversibleMigrationExample < ActiveRecord::Migration[8.0]
  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