There are two tables, the Items table and the Users table, and in order to add the user-id column to the Items table created first, I ran rails db: rollback
twice and then ran rails db: migrate
. However, I got an error that the foreign key does not exist and the user SQL does not exist. (Originally, I should have added a column using add.)
Before creating the Users table, the Items table was created provisionally, so an error occurred that the user-id associated with the Item table does not exist.
For example, suppose you created the first Items table ** as of September 1st **.
class CreateItems < ActiveRecord::Migration[6.0]
def change
create_table :items do |t|
t.references :user, foreign_key: true
This is related to the cause of the error
t.string :name, null: false
t.timestamps
end
end
Omitted below
Suppose you created the second Users table ** as of September 5 **.
class DeviseCreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
## Database authenticatable
t.string :name, null: false
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
The following is omitted
I think the database file will look like db / migrate / 20200905052006_devise_create_users.rb, but the number part "20200905052006" indicates the date and time when the database was created.
Since rails db: migrate
will migrate the database one by one in order from the oldest date and time, in this case the database of the Items table created on September 1 will be migrated first. ..
In other words, if you try to migrate the Items table while the Users table has not been migrated, t.references: user, foreign_key: true
will not be determined to be valid and there will be no foreign key for the user. I get an error message saying that there is no SQL.
If you rename the number in the date and time part, save the file so that the time series is reversed, and then do rails db: migrate
, the Users table will be migrated first and the foreign key does not exist, the user The error that SQL does not exist is resolved.
I couldn't post an accurate error message because I didn't keep a good record of the error. I will be conscious of posting and take notes with a sense of tension.
In the first place, if the column was added using add, the time series would be incorrect and no error would occur.
If it was set to add, it should have been possible to migrate only the usser-id column of the Items table after migrating the User table. It was a mistake to do rails db: rollback
twice and change the column names in the Items table directly.
rails db: migrate
may cause an error.rails db: migrate
is done in order from oldest date and time. (Rails db: rollback cancels the last one migration.)Recommended Posts