Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::IrreversibleMigration exception when reverting migration

I have created the following Active Record Migration that adds and removes some indexes.

class FixIndexes < ActiveRecord::Migration
  def change
    add_index :table1, :field1, :unique => true

    remove_index :table2, :name => "index_table2_on_field1"
    remove_index :table2, :name => "index_table2_on_field2"

    remove_index :table3, :name => "index_table3_on_field1"
    add_index :table3, [:field1, :field2]
  end
end

When I run the migration ($ bundle exec rake db:migrate) it works fine as expected.

Unfortunately when I try to revert the migration ($ bundle exec rake db:rollback) it does not work and raises an ActiveRecord::IrreversibleMigration exception

==  FixIndexes: reverting =====================================================
rake aborted!
An error has occurred, all later migrations canceled:

ActiveRecord::IrreversibleMigration/usr/local/rvm/gems/ruby-1.9.3-p392/gems/activerecord-3.2.14/lib/active_record/migration/command_recorder.rb:42:in `block in inverse'
/usr/local/rvm/gems/ruby-1.9.3-p392/gems/activerecord-3.2.14/lib/active_record/migration/command_recorder.rb:40:in `map'

My questions are:

  1. Why this is an irreversible migration? It just adding and removing some indexes, not data.
  2. It will fix the problem if I use def self.up and def self.down instead of def change?
  3. How can I revert now this changes without adding and removing the indexes manually from MySQL?
like image 800
Rafa Paez Avatar asked Jul 19 '26 14:07

Rafa Paez


1 Answers

Only few commands are reversible(without manual commands) in Rails. And they are

  • add_column

  • add_index

  • add_timestamps

  • create_table

  • create_join_table

  • remove_timestamps

  • rename_column

  • rename_index

  • rename_table

Refer here

Your migration contains remove_index which is not supported by CommandRecorder for Rollback.

If you check this Documentation

Some transformations are destructive in a manner that cannot be reversed. Migrations of that kind should raise an ActiveRecord::IrreversibleMigration exception in their down method.

Which is the case in yours and obviously results in ActiveRecord::IrreversibleMigration exception.

Long Story short: remove_index cannot be reversed without manual commands.

like image 196
Siva Avatar answered Jul 22 '26 03:07

Siva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!