Rails Database Schema Inconsistency
Rails Database Schema Consistency: A Developer’s Guide
aka, Oh no why is schema.rb conflicting all the time!?
How Database Schemas Diverge
“You do it to yourself, you do” – Radiohead
- Multiple developers create migrations in parallel branches
- Column orders differ due to migrations being run in different sequences
- Database restoration from backups followed by migrations
- Migrations aren’t rolled back before switching branches
- Out-of-band database changes without corresponding migrations
Resolving Schema Differences
- Use
rails db:prepareas your primary command for database setup (guide)- Handles both empty and partially migrated states
- Runs schema:load for new databases
- Runs db:seed
- For specific scenarios:
- When in doubt the only thing that should be considered the source of truth is the production
db:schema:dump. Production is reality.
Prevention Strategies
- Development Practices:
- Tools:
- Consider using
fix-db-schema-conflictsgem to maintain consistent column ordering - Newer versions of Rails includes automatic column sorting in schema dumps (PR)
- Consider using
- CI/Testing:
- Consider running
db:resetin CI before tests - Maintaine your seeds.rb file to ensure that it continues to run for developers running (
db:resetordb:prepare). I encourage you to write it so that it is idempotent and can be run again on an existing database as well.
- Consider running