David Oliver David Oliver - 1 month ago 14
Ruby Question

Marking Rails migrations as migrated

I've ended up with 9 migrations effectively duplicated. (I think this is because I installed/updated Gems and/or pulled in their migrations on both my dev and production machines, but am not entirely sure at this stage.)

I moved out one set of the duplicated 9 from the rails directories on the production server, but now that I want to

db:migrate
on production in order to run another migration, I'm getting:

$ bundle exec rake db:migrate RAILS_ENV=production
[DEPRECATION WARNING] Nested I18n namespace lookup under "activerecord.attributes.checkout" is no longer supported
== CreatePages: migrating ====================================================
-- create_table(:pages)
rake aborted!
An error has occurred, all later migrations canceled:

Mysql2::Error: Table 'pages' already exists: CREATE TABLE `pages` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `title` varchar(255), `body` text, `slug` varchar(255), `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB


This is because the migrations have effectively already been run.

I'd rather avoid doing
db:migrate:down
and
db:migrate:up
for each one - I think this will mean data in the production database is lost. (A couple of static pages in Spree in this case.)

Is there a way I can tell this installation of Rails to forget all outstanding migrations, effectively marking all outstanding migrations as done?

Answer

You can add the timestamps of the migrations to the schema_migrations table. However why is that table missing from the database or missing the rows it needs?

It is likely to be the case that this particular migration has got half way through and failed, thus when you are trying to run it again the first part of the migration will not work as it has been done previously. This is a limitation of MySQL as it can't rollback migration changes that fail part of the way through. Postgres on the other hand can rollback structural changes to the database thus avoiding this issue.