4

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

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Michael
  • 119
  • 1
  • 13
  • 1
    Possible duplicate: https://stackoverflow.com/questions/31552604/reversible-migration-for-change-column-default-from-not-having-any-default-in-ra – olmstad Jul 26 '16 at 18:14

2 Answers2

5

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
olmstad
  • 686
  • 5
  • 9
  • I tried your answer but got a Postgresql specific error while running the migration with your recommended changes. Does PG not accept this 'type' of migration? – Michael Jul 26 '16 at 18:55
  • No, it's not postgres specific, it's Rails version specific. I've updated my answer. – olmstad Jul 26 '16 at 19:28
  • Sorry, should have explicitly written 4.2, will do for any future reader of this. And Rails 5 looks way more simpler, thanks for follow up. – Michael Jul 26 '16 at 20:39
4

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.

ChrisBarthol
  • 4,871
  • 2
  • 21
  • 24