bokunonikki.net
JP / EN

マイグレーションを削除した時にnofileと表示されてしまった場合の対処法

Wed Jul 26, 2017
Fri Nov 24, 2017

まず最初に、消したいマイグレーションファイルのIDを調べる。

1
$ rake db:migrate:status

を実行し、現状を把握する。

1
2
3
4
5
6
7
database: petipeti_development

 Status   Migration ID    Migration Name
--------------------------------------------------
  down    2017072605442   Create gambles0
   up     20170726054542  ********** NO FILE **********
  down    20170726074346  Create gambles

今回の場合は、これが消したいファイルです。

1
up     20170726054542  ********** NO FILE **********

ファイルがないのですから、とりあえずマイグレーションファイルを作ります。形式はマイグレーションid_tmp.rbとしてください。

1
20170726054542_tmp.rb

そして、先ほど作った20170726054542_tmp.rbに下の内容を書き込みます。

1
2
3
4
class Tmp < ActiveRecord::Migration
  def change
  end
end

rails5の場合は

1
2
3
4
class Tmp < ActiveRecord::Migration[5.0]
  def change
  end
end

これをしないとターミナルで

1
2
Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:
  class Tmp < ActiveRecord::Migration[4.2]

とエラーが表示される。

ここまでの作業が終わったらマイグレーションの状態を確認します。

1
2
3
4
5
6
7
8
$ rake db:migrate:status
database: petipeti_development

 Status   Migration ID    Migration Name
--------------------------------------------------
  down    2017072605442   Create gambles0
   up     20170726054542  Tmp
  down    20170726074346  Create gambles

先ほどで、no fileだった奴がTmpに変わっていることを確認できたと思います。

次にこのマイグレーションファイルをdownさせます。

1
$ rake db:migrate:down VERSION=20170726054542

ちゃんとできたか確認します。

1
2
3
4
5
6
7
8
$ rake db:migrate:status
database: petipeti_development

 Status   Migration ID    Migration Name
--------------------------------------------------
  down    2017072605442   Create gambles0
  down    20170726054542  Tmp
  down    20170726074346  Create gambles

downを確認したら、マイグレーションファイルを削除します。

1
2
3
4
5
6
7
$ rails destroy migration Tmp
database: petipeti_development

 Status   Migration ID    Migration Name
--------------------------------------------------
  down    2017072605442   Create gambles0
  down    20170726074346  Create gambles

バッチリうまくいきました。

See Also