April 30, 2019
This blog is part of our Rails 6 series.
Rails allows us to use different databases using the database.yml
config file.
It uses sqlite3 as the default database when a new Rails app is created. But it
is also possible to use different databases such as MySQL or PostgreSQL. The
contents of database.yml
change as per the database. Also each database has a
different adapter. We need to include the gems pg
or mysql2
accordingly.
Before Rails 6, it was not possible to change the contents of database.yml
automatically. But now a
command has been added to do this
automatically.
Let's say our app has started with sqlite and now we have to switch to MySQL.
$ rails db:system:change --to=mysql
conflict config/database.yml
Overwrite /Users/prathamesh/Projects/reproductions/squish_app/config/database.yml? (enter "h" for help) [Ynaqdhm] Y
force config/database.yml
gsub Gemfile
gsub Gemfile
Our database.yml
is now changed to contain the configuration for MySQL
database and the Gemfile
also gets updated automatically with addition of
mysql2
gem in place of sqlite3
.
This command also takes care of using proper gem versions in the Gemfile when the database backend is changed.
If this blog was helpful, check out our full blog archive.