Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 879
Michael Avatar asked Oct 26 '25 09:10

Michael


2 Answers

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
like image 192
olmstad Avatar answered Oct 29 '25 00:10

olmstad


When you rollback what do you expect the default to be? From the migration you wrote it is not explicit enough on what the default to should be set to. Adding from and to should fix the issue but in my opinion with migrations like this it is better to be explicit on what the up and down methods are doing.

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

Then when you rollback it will set the default to nil and you can edit the migration to false and rake db:migrate again.

like image 36
ChrisBarthol Avatar answered Oct 28 '25 22:10

ChrisBarthol



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!