Home>

I'm developing a web application using Rails, but I'm having trouble solving the error when running rails db:migrate.
The error resulted in the model name used in the second argument of add_reference being mistakenly entered in the migration file. I entered sub_places where I should have entered subplaces.
At that time, the error message displayed on the terminal will be 1 below.
An error occurred during migration, so when I checked rails db:migrate:status, the status of the file was still dowm. Since the migration file was down, rewriting the spelling and running rails db:migrate again, the following error message 2 appears.
Probably, even though the migration file is down, the parts other than add_reference :posts, :subplace, foreign_key: true are reflected in the database.
The software Sequel Pro used for database management reflects the contents of the migration file.
Is there a solution for this situation?
Thanks for your response.

Error message 1
Mysql2::Error: Table'App name_development.sub_places' doesn't exist: SHOW FULL FIELDS FROM `sub_places`
Error message 2
Mysql2::Error: Duplicate column name'lunch_name': ALTER TABLE `posts` ADD `lunch_name` varchar(255)
Applicable source code
#Migration file
class AddDetails2ToPosts
What I tried

https://qiita.com/niyomong/items/22fa60657ea8ee478647a
Please refer to this article.
Once empty the migration file, run rails db:migrate, run rails db:rollback with status up, fix spelling and run rails db:migrate again.
The result is the same as error message 2 above.

  • Answer # 1

    I solved it by directly deleting unnecessary columns using SQL
    ・Points that took time
    The foreign key could not be simply deleted because it had a foreign key constraint.
    ALTER TABLE posts DROP COLUMN foreign key;
    Before
    SHOW CREATE TABLE posts;
    (To the right of CONSTRAINT is the foreign key constraint name)
    Check the foreign key constraint name with
    ALTER TABLE posts DROP FOREIGN KEY foreign key constraint name;
    The foreign key was successfully deleted by executing.
    After that, I could restore the schema file to the state before the change and reflect the migration file with rails db:migrate.