Search code examples
ruby-on-railspostgresqlrails-migrationsruby-on-rails-5

Reorder/change timestamp on migration files


One of my migration files is referencing another table/model that will will be created further down the migration sequence.

Postgres doesn't like that:

PG::UndefinedTable: ERROR: relation "users" does not exist

So I wonder if there are any potential problems to manually reorder the migration files (by inventing new timestamps/prefixes)?

The affected tables are already down migrated.


Solution

  • When you run rake db:migrate command it compares schema_migrations table and migration files located in db/migrate folder. All the migrations which were not executed receive MigrationClass#up call then.

    So starting from the point when your code is already published and/or migrations are run by other users, changing your migrations timestamps/names may lead to unprocessable migration procedure (as schema_migrations will treat a migration with changed timestamp as new, unprocessed one, and try to process it "again"). Possible workaround for this would be to comment the contents of up method for a while and uncomment it back after migrations are done. For fun you can also manipulate schema_migrations table directly from your db console (adding or removing necessary records). Both of these ways smells like a hack though.

    Until then... Everything should work flawlessly.