I have some migrations that need to be run. But when I rake db:migrate
the following error occurs.
Mysql2::Error: Table already exists
.
This happens for 4-5 times as the tables already exist but the schema_migrations
table seems to be not in sync with the application.
I have a production dump in my db and I don't want to drop tables and lose data. What I am currently doing is modifying the schema_migrations
table and adding these conflicting migration numbers in there manually and then running rake db:migrate
again until the errors go away and then my new migrations start to run. But that doesn't seem right.
Is there any feasible solution to this other than what I mentioned which doesn't involve dropping the database or losing data?
For such type of migration you can check for table_exists
before create table in migration using
class Migrationclassname < ActiveRecord::Migration
def up
if table_exists?(:table_name)
# Some changed if required
else
# create table
end
end
def down
end
end
This happens for 4-5 times as the tables already exist but the schema_migrations table seems to be not in sync with the application.
You can run rake db:schema:dump
to have your database in the form of what your schema file says. And if the mentioned tables aren't shown in the schema file, then you can surely create them by running rake db:migrate
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.