Search code examples
ruby-on-railsrails-activerecordreverserollbackrails-migrations

How did I get a IrreversibleMigration?


I have already added 'activated' as a boolean in my User table. I forgot to add it to false as default, so I generated this migration :

rails g migration add_default_to_users_activated

I then added line 3 here :

class AddDefaultToUsersActivated < ActiveRecord::Migration
  def change
    change_column_default :users, :activated, true
  end
end

I then ran the migration w/out any problems. I realized I should have added 'false' instead of 'true', so I wanted to reverse the migration and just change the add_default_to_users_activated.rb file to 'false' However when I run

rake db:rollback

rake gets aborted due to ActiveRecord::IrreversibleMigration.

But what is the mechanism I have set in, that prevents the migration from being reverted and how do I fix it?

EDIT: I'm running rails 4.2


Solution

  • It's a bad idea to change your migrations before a rollback. According to Rails 5 documentation change_column_default requires from and to attributes to be reversible.

    In Rails 5 migration should look like this:

    class AddDefaultToUsersActivated < ActiveRecord::Migration
      def change
        change_column_default :users, :activated, from: nil, to: false
      end
    end
    

    In Rails 4 you should separate change method to up and down as @ChrisBarthol suggested, because from and to options was not introduced yet:

    class AddDefaultToUsersActivated < ActiveRecord::Migration
      def up
        change_column_default :users, :activated, true
      end
      def down
        change_column_default :users, :activated, nil
      end
    end