LoginSignup
7
3

More than 5 years have passed since last update.

カラム削除後にロールバック(rollback)すると型がなくてエラーになる

Last updated at Posted at 2018-09-06

railsでカラムを削除する時にはremove_columnを使って削除します。

class RemoveEmailFromUsers < ActiveRecord::Migration
  def change
    remove_column :users, :email
  end
end

しかし、この変更を取り消したく、rake db:rollbackでロールバックを行いました。

次の瞬間。。

ActiveRecord::IrreversibleMigration: 

remove_column is only reversible if given a type.

型が無いよと怒られてしまいました。

なので、ロールバックを行いたい場合は、型を追加して、

class RemoveEmailFromUsers < ActiveRecord::Migration
  def change
    remove_column :users, :email, :string #型を追加
  end
end

再度, rake db:rollbackを実行してあげれば無事カラムが復活します。

また、マイグレーションファイルを作る際に、
rails g migration RemoveEmailFromUsersではなく、
rails g migration RemoveEmailFromUsers emailというように最後にしっかりとカラムを指定してあげると、自動的に変更したいカラムと型が設定されるので幸せになれます。

参考: https://qiita.com/HiromiKai_Green/items/7cedfdabbf7db750fc8c

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3