DEV Community

Cover image for How to use and integrate PostgreSQL to Rails
Jitendra Chavhan
Jitendra Chavhan

Posted on

How to use and integrate PostgreSQL to Rails

Learn how to use PostgreSQL with your Ruby on Rails application, instead of the default SQLite database. SQLite is an easy-to-configure, lightweight product which ships with Ruby on Rails by default. However, PostgreSQL is a more robust solution which provides more advanced features, scaling, and stability, which may make it more suitable for your Ruby on Rails project.

Step 1: Update the Gemfile

Open the Gemfile which is locate in your root directory and add the following gem

gem 'pg'

Save this file & close it and run the bundle install command on your terminal

Step 2: Configure the database connection

Open the database.yml file which is location in your root directories config folder and update the following configuration for development, test and production environments to use PostgreSQL.

default: &default
  adapter: postgresql
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000
  host: localhost
  username: <%= ENV['PG_USERNAME'] %>
  password: <%= ENV['PG_PASSWORD'] %>
  <<: *default
  database: app_development
  <<: *default
  database: app_test

  <<: *default
  database: app_production

Enter fullscreen mode Exit fullscreen mode

After updating the configuration of database.yml file save and close it.

Step 3: Create the database

After updating the configuration, run the following command in your terminal to create the PostgreSQL database:

rails db:create

This command will create the database based on the configuration provided in database.yml.

Step 4: Migrate the database

If you have existing migrations in your Rails application, you'll need to migrate the database to create the necessary tables in PostgreSQL. Run the following command:

rails db:migrate

This will execute any pending migrations and update the PostgreSQL database schema.

Step 5: Verify the integration

To ensure the integration was successful, start your Rails application using the rails server command and verify that it connects to the PostgreSQL database without any errors.

rails s

Congratulations! You have successfully integrated PostgreSQL (pg) with your Rails application. You can now take advantage of PostgreSQL's advanced features and performance benefits in your Rails application.

Top comments (0)