0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

railsのmigration fileが外部キーでdown出来ない時の対処法

Posted at

ruby 2.6.6
rails 6.0.3
catalina 10.15.5

railsのmigration fileが外部キーでdown出来ない時の対処法がググってもあまり情報が出て来なかったので、後学のために。
要らないmigration fileを削除したく以下コマンド叩く。

$ rails db:migrate:down VERTION=migration_file_id

すると下記エラー

Mysql2::Error: Cannot drop table 'stores' referenced by a foreign key constraint

エラーメッセージに外部キーと書いてあるので、まずは無効化。の前にdatabase選択
以下コマンド後、少し解説

mysql> show databases;
mysql> use database名;
# 外部キー無効化
mysql> set foreign_key_checks = 0;
mysql> show tables;
mysql> select * from schema_migrations;
mysql> select * from schema_migrations where version = 'migration_file_id';
mysql> delete  from schema_migrations where version = 'migration_file_id';
mysql> select * from schema_migrations;
$ rails db:migrate:status
$ rails db:rollback

ここまでコマンドのみ

以下解説

mysql> select * from schema_migrations;
+----------------+
| version        |
+----------------+
| 20200714085643 |
| 20200715061816 |
+----------------+
2 rows in set (0.00 sec)

消したいのはこれ → 20200714085643

mysql> select * from schema_migrations where version = '20200714085643';
+----------------+
| version        |
+----------------+
| 20200714085643 |
+----------------+
1 row in set (0.00 sec)
mysql> delete  from schema_migrations where version = '20200714085643';
Query OK, 1 row affected (0.00 sec)
mysql> select * from schema_migrations;
+----------------+
| version        |
+----------------+
| 20200715061816 |
+----------------+
1 row in set (0.01 sec)
# 20200714085643が消えた
# 外部キー有効化
mysql> set foreign_key_checks = 1;
# 最新のマイグレーションファイルのバージョンが指定データベースのschema_migrationsテーブルから削除される
$ rails db:rollback

downしたいファイルが複数ある場合は下記コマンド

# 5つのマイグレーションファイルをロールバックしたい時
$ rails db:rollback STEP=5

これでrails db:migrate:statusすればdownになっているはず。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?