Sam
Sam

Reputation: 1253

rails migrations changed unrelated columns

I ran migrations which did not touch a given table in any way. After running it, 3 foreign keys which reference that table were removed and their corresponding columns changed from bigints to integers.

This has resulted in a situation where

an example:

# the most recent migration related to the column
# but an old one (not only executed on dev branch)
def up
  # ...
  change_column :abc, :table_a_id, :bigint
  # ...
# development db/schema.rb
# ...
create_table "abc", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
  t.integer "table_a_id"
# ...
# production db/schema.rb
# ...
create_table "abc", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
  t.bigint "table_a_id"
# ...
add_foreign_key "abc", "table_a"
# ...

I have run rails db:reset, and nothing changed.

AFAIK, I cannot create migrations to correct these changes, since such migrations would fail in production. Is this correct? If so, what can I do to rescue the commit and prevent this from happening again? Can I manually revert my schema.rb? And why/how did this happen?

Upvotes: 0

Views: 340

Answers (1)

Mark
Mark

Reputation: 6445

Useful info on rolling back migrations:

How to rollback a specific migration?

Long story short, yes you can reset the structure of your database and schema.rb file. You may lose any data from columns you deleted, however if your intention is getting your schema.rb file to look right so it passes any pre-deployment hooks then rolling back and reseting your schema.rb file is the way to go:

rake db:rollback

Will revert your latest migration. If this migration isn't your problem one, then try:

rake db:migrate:down VERSION=20100905201547

With the correct version timestamp that's present in the filename of the migration. Once you've done that, you'll have fixed the database you have locally, but your schema file will still be out of sync. To fix this run

rake db:schema:dump

Finally if you're still having headaches, and as a last option fix, you can just

git checkout db/schema.rb

And you'll get the latest version of db/schema.rb that was pushed up to the branch that you're working on. Or alternatively:

git checkout origin/master db/schema.rb

To reset your schema.rb file to master. As long as you don't push up any broken migrations, and your schema.rb file is in order, then you won't break anything for anyone else

Upvotes: 1

Related Questions