etsuxのブログ

自分がハマったことなどを記録しています。

Rails+MySQLの環境で、referencesがdb:migrateでエラー

以下の環境を使用している。

referencesを使用してdb:migrateをするとデータ型が合わないエラーになる。

Caused by:
ActiveRecord::MismatchedForeignKey: Column `test_id` on table `temps` does not match column `id` on `tests`, which has type `bigint(20)`. To resolve this issue, change the type of the `test_id` column on `temps` to be :bigint. (For example `t.bigint :test_id`).
Original message: Mysql2::Error: Cannot add foreign key constraint: CREATE TABLE `temps` (`id` bigint NOT NULL AUTO_INCREMENT PRIMARY KEY, `test_id` bigint, `work_id` bigint, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL,  INDEX `index_temps_on_test_id`  (`test_id`),  INDEX `index_temps_on_work_id`  (`work_id`), CONSTRAINT `fk_rails_dc13fd614b`
FOREIGN KEY (`test_id`)
  REFERENCES `tests` (`id`)
, CONSTRAINT `fk_rails_xxxxxxxxxx`
FOREIGN KEY (`work_id`)
  REFERENCES `works` (`id`)
)

生成しているtempsのCREATE TABLE文のidはbigintになっているので、testsのidもbigintとなっているはず。

なのにデータ型はbigint(20)だと言っている。

mysql> create table test1 (col1 bigint primary key);
Query OK, 0 rows affected (0.14 sec)

mysql> show create table test1;
+-------+------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                   |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------+
| test1 | CREATE TABLE `test1` (
  `col1` bigint(20) NOT NULL,
  PRIMARY KEY (`col1`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

bigintはbigint(20)になるのか。データ型が合わない?問題はないと思うのだけれど?

mysql> create table test2 (col1 bigint primary key, col2 bigint, constraint fk_col2 foreign key (col2) references test1 (col1));
Query OK, 0 rows affected (0.05 sec)

うまくいくよね、やっぱり。

 

よく考えたら、create tableの順序を間違えていた。

  1. tests
  2. temps → testsとworksをreferences
  3. works

正しい順序にしたらエラーは解消。

  1. tests
  2. works
  3. temps → testsとworksをreferences

エラーメッセージが具体的過ぎたので、bigintばかり確認しすぎた。

もう少し、referencesに誤りがあるかも~程度のメッセージなら、迷路に入らなかったかな?