ご覧いただきありがとうございます。
現在インスタのようなrailsアプリを作成しており今回photoモデルを追加しようとしたところ
mysqlでエラーが出てきました。エラー自体はすでに解消ずみだったのですが全体の流れが
イマイチ理解できなかったのでどなたかお分かりになる方ご教授いただけましたら幸いです。
エラー内容
Mysql2::Error: Cannot add foreign key constraint
mysql> SHOW ENGINE INNODB STATUS\Gで詳しいエラー内容を確認
2021-11-02 07:28:38 0x7f45a84e4700 Error in foreign key constraint of table app_development/photos: FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ): Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. Note that the internal storage type of ENUM and SET changed in tables created with >= InnoDB-4.1.12, and such columns in old tables cannot be referenced by such columns in new tables. Please refer to http://dev.mysql.com/doc/refman/5.7/en/innodb-foreign-key-constraints.html for correct foreign key definition.
postのデータベース中身
+------------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+----------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | content | text | YES | | NULL | | | user_id | int(11) | NO | MUL | NULL | | | created_at | datetime | NO | | NULL | | | updated_at | datetime | NO | | NULL | | +------------+----------+------+-----+---------+----------------+ 5 rows in set (0.01 sec)
解決方法
以下記事を参考にしました。
https://stackoverflow.com/questions/42422894/cannot-add-foreign-key-constraint-error-when-running-rails-migration
foreign_keyをfalseにする --> t.references :post, foreign_key: false
データベースをリセットします --> rails db:migrate:reset,
foreign_keyをtrueに戻します --> t.references :post, foreign_key: true
DBを移行します --> rails db:migrate
これで確かにエラーは解消したのですが正直何が起こったのかよくわからなかったため
お分かりになる方、どなたかこの一連の流れを解説等していただけましたら大変助かります。
宜しくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/11/11 09:09