[RUBY] [Rails] Error StandardError: An error has occurred, all later migrations canceled: Column `Foreign key name` on table` Table name` does not match column ʻid` on `Table name`

error contents

$ rails db:migrate

An error that occurs when the above command is executed. The error notation in the terminal is as follows. image.png

Partial excerpt of error text.


Column `user_id` on table `items` does not match column `id` on `users`, which has type `bigint(20)`. To resolve this issue, change the type of the `user_id` column on `items` to be :bigint. (For example `t.bigint :user_id`).

When I translate a part of the error sentence ...

Error sentence translation.


table`items`Column`user_id`But`users`Column`id`Does not match. To solve this problem`items`of`user_id`Column type:Change to bigint.(For example`t.bigint :user_id`)。

This time, the column specified as the foreign key in the items table does not match the referrer! That's the error.

Remedy (hypothesis)

In conclusion, Rails recommends references type when using foreign keys, so you don't need to use bigint type.

Since the point of this error is ** cannot be referenced **, it can be hypothesized that there is a problem in the order in which the migration files are created.

What is the order of creating migration files?

Tables that use foreign keys (tables that describe the references type) and referenced tables may not be able to be referenced depending on the creation order, and this error occurred due to an incorrect creation order.

The creation order is (1) the table on the referenced side → (2) the table that uses the foreign key (the table that describes the references type). The workaround can be solved by modifying the creation date and time of the migration file.

Remedy (temporary verification)

image.png The solution is to make the number part of the attached image larger in the table that uses the foreign key than in the referenced table.

It's an error that is a little hard to guess from the error.

In this case, if create_items is 20200909000000, then 20200909100000 is fine. By the way, ** the first 4 digits are the Christian era, and the next 4 digits are the month and day **.

Finally

I think this error is likely to occur when the number of tables increases. However, if you know the target law, you can solve it without any problem, so please refer to it!

Recommended Posts

[Rails] Error StandardError: An error has occurred, all later migrations canceled: Column `Foreign key name` on table` Table name` does not match column ʻid` on `Table name`
Error in docker rails db: migrate (StandardError: An error has occurred, all later migrations canceled :)
What to do when an error occurs in rails db: migrate ((StandardError: An error has occurred, this and all later migrations canceled :))
What to do when an error (StandardError: An error has occurred, this and all later migrations canceled:) appears in rails db: migrate