Working across teams, we always need to keep the database in sync with code changes, with migrations across branches and more.
To sync up, or when setting up a new database, we run the following commands:
Rails 6 adds
to take care of the above for us,
and prepare the database for use
of the required database.
Problems with just migrate
rails db:migrate when the database doesnt exist,
db:prepare internally catches
and then runs
In other words,
if the database is correctly configured,
db:prepare will just run the migration,
if the database already exists.
If the database does not exist,
db:prepare ensures that it is created,
migrated and seeded with data.
Behaviour depending on presence of database
When database is present:
This executed migrations on the existing database.
When database is not present:
This created the database and populated seed data.
Important bit is that
db:prepare always runs in an idempotent way.
This is useful when being utilized in CI scripts, staging deployments, and more.