Search code examples
mysqlruby-on-railsmysql2

I need some rails migration help for adding/removing foreign_key


On my local machine with I run rake db:migrate there are a couple add_foreign_key constraints removed from the db/schema.rb file but when I run the same command on my dev server rails adds them back in. I've checked the mysql & rails versions and they are the same. Can someone guide/tell me what is going on here?

local machine:

$ mysql --version
mysql  Ver 14.14 Distrib 5.7.23, for osx10.13 (x86_64) using  EditLine wrapper

$ rails --version
Rails 4.2.6

$ gem list --local mysql2
*** LOCAL GEMS ***
mysql2 (0.4.4)

dev server:

$ mysql --version
mysql  Ver 14.14 Distrib 5.7.23, for Linux (x86_64) using  EditLine wrapper

$ rails --version
Rails 4.2.6

$ gem list --local mysql2
*** LOCAL GEMS ***
mysql2 (0.4.4)

Solution

  • First you need to understand that db/schema.rb represents ActiveRecord's understanding of your database the last time the db:schema:dump Rake task was run. The database's structure (as seen in db/schema.rb) may or may not exactly match what you see in your db/migrate directory: migrations could have been added and removed, database options changed, aliens, things could have been manually changed (i.e. outside migrations), ...

    Looks like FKs were added in your development database but not your production database or they were removed from production (or ignored) so your databases are out of sync. Check your production database using the mysql CLI tool and see if the FKs are there; if they're not then synchronized your databases by hand or with a production-only migration. You'll probably want to do this on an exact copy of your production database first so that you can make sure that all the FKs are valid before unleashing chaos on a production system.


    Similar things apply to db/structure.sql if you use the "raw SQL" format for managing your schema.