Rails 6 adds rails db:system:change command

Let’s create a new Rails app.

rails new sample

Our database.yml contains configuration specific to sqlite3 because rails creates the application with sqlite3 as the default database.

Now if we want to change our database from sqlite3 to PostgreSQL or any other database. Then, we have to manually modify our database.yml to add PostgreSQL related configuration.

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: sample_development

test:
  <<: *default
  database: sample_test

production:
  <<: *default
  database: sample_production
  username: sample
  password: <%= ENV['SAMPLE_DATABASE_PASSWORD'] %>      

And along with this, we also need to remove sqlite3 adapter and add pg gem to our Gemfile.

gem 'pg'

Now we need to run bundle install to install the pg adapter.

To automate this process, Rails 6 has added rails db:system:change command.

It takes one argument to which specifies the database type. For example, if we want to change our database to PostgreSQL then to will be postgresql.

This command will automatically update our database.yml and Gemfile for the adapter based on the to option provided.

Let’s say, if we want to change the database to PostgreSQL then we need to run following command:

>rails db:system:change --to=postgresql
    conflict  config/database.yml
Overwrite /Users/romil/Desktop/work/sample/config/database.yml? (enter "h" for help) [Ynaqdhm] Y
       force  config/database.yml
        gsub  Gemfile
        gsub  Gemfile    

Now the only thing we need to do is run bundle install and we are all set.

Need help on your Ruby on Rails or React project?

Join Our Newsletter