LoginSignup
7
3

More than 3 years have passed since last update.

Mysql2::Error: Cannot add foreign key constraint

Posted at

本番環境にて、マイグレーションを実行しようとした時に、マイグレーションに失敗した。

エラーの内容

rails aborted!
StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: Cannot add foreign key constraint: CREATE TABLE `messages` (`id` int AUTO_INCREMENT PRIMARY KEY, `content` varchar(255), `image` varchar(255), `group_id` int, `user_id` int, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL,  INDEX `index_messages_on_group_id`  (`group_id`),  INDEX `index_messages_on_user_id`  (`user_id`), CONSTRAINT `fk_rails_841b0ae6ac`
FOREIGN KEY (`group_id`)
  REFERENCES `groups` (`id`)
, CONSTRAINT `fk_rails_273a25a7a6`
FOREIGN KEY (`user_id`)
  REFERENCES `users` (`id`)
) ENGINE=InnoDB
/var/www/chat-space2/db/migrate/20190605081736_create_messages.rb:3:in `change'
/var/www/chat-space2/bin/rails:9:in `require'
/var/www/chat-space2/bin/rails:9:in `<top (required)>'
/var/www/chat-space2/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'

Caused by:
ActiveRecord::StatementInvalid: Mysql2::Error: Cannot add foreign key constraint: CREATE TABLE `messages` (`id` int AUTO_INCREMENT PRIMARY KEY, `content` varchar(255), `image` varchar(255), `group_id` int, `user_id` int, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL,  INDEX `index_messages_on_group_id`  (`group_id`),  INDEX `index_messages_on_user_id`  (`user_id`), CONSTRAINT `fk_rails_841b0ae6ac`
FOREIGN KEY (`group_id`)
  REFERENCES `groups` (`id`)
, CONSTRAINT `fk_rails_273a25a7a6`
FOREIGN KEY (`user_id`)
  REFERENCES `users` (`id`)
) ENGINE=InnoDB

原因
マイグレーションファイルの実行の時系列がおかしかったからであった。

解決方法
マイグレーションファイルの名前(日付)をrenameして、時系列を変更すればよい。
今回の場合、messageテーブルのマイグレーションファイルの時系列を最後に持って来れば解決できる。
https://gyazo.com/25a0e44be659fceebed88fb7226bd9e4

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