0
0

More than 1 year has passed since last update.

ロールバックが出来ないパターン

Last updated at Posted at 2021-11-03

カラムの型を変更した

その後ロールバックしたらなぜかできなかったので

開発環境

ruby 2.6.5
Ruby on Rails 5.2.5

本題

 t.string :name, null: false

上のようなカラムの型を変えようと思い

マイグレーションファイルを作成
 def change
    change_column :tasks, :name, :text, (←変更点)  null: false
 end

上記のようにマイグレーションファイルを作成
そして rails db:migrate

その後 rollback してみるとエラーが発生

== 20210601072158 ChangeStyleNameColumn: reverting ============================
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:



This migration uses change_column, which is not automatically reversible.
To make the migration reversible you can either:
1. Define #up and #down methods in place of the #change method.
2. Use the #reversible method to define reversible behavior.


/Users/isamutatsuya/workspace/manyoTest/db/migrate/20210601072158_change_style_name_column.rb:3:in `change'
/Users/isamutatsuya/workspace/manyoTest/bin/rails:9:in `<top (required)>'
/Users/isamutatsuya/workspace/manyoTest/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'

Caused by:
ActiveRecord::IrreversibleMigration: 

This migration uses change_column, which is not automatically reversible.
To make the migration reversible you can either:
1. Define #up and #down methods in place of the #change method.
2. Use the #reversible method to define reversible behavior.

今まで割と雰囲気でやっていたけど
def change で使えるメソッドには
ロールバックに対応しているものと
対応していないものがあるらしい

今回の change_column メソッドはまさに
ロールバックに対応していないものだった

以下の記事を参考にさせていただいくと

対応してるしてないは
このようにいろいろとある

ちなみに

  def up
    change_column :tasks, :name, :text, null: false
  end

  def down
    change_column :tasks, :name, :string, null: false
  end

こうやって up メソッドや down メソッドを活用したら
ロールバックにも対応するマイグレーションファイルが作れる。

まあただロールバック対応のマイグレーションファイルを作っていいことがあるかどうかは
今の自分のレベルではわかりません

0
0
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
0
0