LoginSignup
6
2

More than 3 years have passed since last update.

【Rails】rails db:migrate できない!? Mysql2::Error: Cannot add foreign key constraint

Last updated at Posted at 2020-05-08

 目的

一気にdbに書き込んでマイグレーションを反映させるぞ!
rails db:migrate
をしてもDBに反映されない。。。エラーにハマったので備忘録として。

エラー文

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

Mysql2::Error: Cannot add foreign key constraint: CREATE TABLE `oreders` (`id` int AUTO_INCREMENT PRIMARY KEY, `buyer_user_id_id` int NOT NULL, `item_id` int NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL,  INDEX `index_oreders_on_buyer_user_id_id`  (`buyer_user_id_id`),  INDEX `index_oreders_on_item_id`  (`item_id`), CONSTRAINT `fk_rails_3116d56c37`
FOREIGN KEY (`buyer_user_id_id`)
  REFERENCES `buyer_user_ids` (`id`)
, CONSTRAINT `fk_rails_8199fc7446`
FOREIGN KEY (`item_id`)
  REFERENCES `items` (`id`)
) ENGINE=InnoDB

何が起きているの?

①外部キーを設定しているが、そもそもその参照先がないぞ!言われている
②item_idってなんだ?と言われている

解決①

アイテムに紐づくデータなのに、アイテムが無いよということを言われている
しかしちゃんと作ってあるが。。。
問題は「タイムスタンプの順番」にあった

つまり上から順番に、DBに反映させていくので
ファイル名の時系列がおかしいとエラーが出る。

↓改善後
スクリーンショット 2020-05-08 17.50.25.png

:point_up:
これならitemsテーブルができた後にordersテーブルを書くのでエラーは起きない。

解決②

item_idってなんだ?と言われている
→item に変えることでエラー解消

そもそも…外部キーとは

  • 一方のテーブルに加えた変更が自動的に他テーブルにも反映する
  • 外部キーを持つテーブル間に親子関係を定義する

つまり…キーをもとに、二つのテーブルを紐付ける
※参照元, 参照先のキーの型が同じであることも必須 これがエラーの原因になることも

参考文献

https://kengotakimoto.com/post-2152/#toc13
https://qiita.com/okamoto_ryo/items/8aceacdd81d079e8a120

6
2
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
6
2