今回はremove_columnにbulk: trueオプションを付与すると、not reversibleの警告が吐かれてしまう際の解決法についてまとめたいと思います。この現象に関してはRubocop上にissueが立っており、copの作成者からの回答が載っていました。
↓ ↓ ↓
問題の再現
まずはこの現象を再現してみましょう。
以下のようなマイグレーションファイルを作成し、Rubocopを実行します。
class AddAndRemoveColumnsToTable < ActiveRecord::Migration[6.0]
def change
remove_column :table_name, :before_value, :text
remove_column :table_name, :after_value, :text
add_column :table_name, :differences, :jsonb
end
end
するとbulk: tureの使用を推奨する警告文が表示されるはずです。
C: Rails/BulkChangeTable: You can combine alter queries using bulk: true options.
この警告を元にbulk: trueを用いて書き直し、再度Rubocopを実行してみます。
class AddAndRemoveColumnsToTable < ActiveRecord::Migration[6.0]
def change
change_table :table_name, bulk: true do |t|
t.remove :before_value
t.remove :after_value
t.jsonb :differences
end
end
end
警告が解消されると思いきや、別の警告が表示されるようになってしまいました。
C: Rails/ReversibleMigration: change_table(with remove) is not reversible.
警告文を読むと、not reversible(元に戻せないこと)が原因のようですね。
解決方法
not reversibleはupメソッドとdownメソッドを明示的に記載することで解消できます。
先ほどのマイグレーションファイルをupメソッドとdownメソッドを用いて書き換えてみましょう。
class AddAndRemoveColumnsToTable < ActiveRecord::Migration[6.0]
def up
change_table :table_name, bulk: true do |t|
t.remove :before_value
t.remove :after_value
t.jsonb :differences
end
end
def down
change_table :table_name, bulk: true do |t|
t.text :before_value
t.text :after_value
t.remove :differences
end
end
end
これにより、再度Rubocopを実行しても警告が表示されなくなりました。
まとめ
- remove_columnにbulk: trueオプションを使用すると、not reversibleの警告が新たに表示されてしまう
- not reversibleはupメソッドとdownメソッドを使用することで解消できる
参考
- Rails: change_table に bulk: true のオプションを推奨する Cop が欲しい #29
- remove_column should not be included in BulkChangeTable cop #110
今回はremove_columnにbulk: trueオプションを付与すると、not reversibleの警告が吐かれてしまう際の解決法について解説しました。bulk: trueはあくまでオプションであるため、この記述が冗長に感じる場合は警告を無視してしまっても良いのかもしれません。