Rails 6 has added a way to change the database of the app

Prathamesh Sonpatki

By Prathamesh Sonpatki

on 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.

1$ rails db:system:change --to=mysql
2    conflict  config/database.yml
3Overwrite /Users/prathamesh/Projects/reproductions/squish_app/config/database.yml? (enter "h" for help) [Ynaqdhm] Y
4       force  config/database.yml
5        gsub  Gemfile
6        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.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.