PostgreSQL is a popular open-source relational database management system. In this article, we will guide you through the process of using PostgreSQL with your Ruby on Rails application on Ubuntu 20.04.

Before we begin, make sure that you have a Ruby on Rails application set up on your Ubuntu 20.04 system and that the necessary dependencies are installed. You will also need to be logged in as a user with sudo privileges.

Install the PostgreSQL package

The first step is to install the PostgreSQL package from the default Ubuntu repositories. To do this, run the following command in the terminal:


sudo apt update
sudo apt install postgresql postgresql-contrib

This will install the PostgreSQL package and the necessary dependencies on your system.

Create a PostgreSQL user and database

After installing PostgreSQL, we need to create a new user and database that will be used by our Ruby on Rails application. To do this, log in to the PostgreSQL shell as the "postgres" user using the following command:

sudo -u postgres psql

In the PostgreSQL shell, run the following commands to create a new user and database:


CREATE USER rails_user WITH PASSWORD 'password';
CREATE DATABASE rails_database OWNER rails_user;

Replace "rails_user" and "rails_database" with the actual names of the user and database that you want to create. Replace "password" with a strong password for the "rails_user" user.

Configure your Ruby on Rails application

After creating the PostgreSQL user and database, we need to configure our Ruby on Rails application to use them. To do this, open the "config/database.yml" file using your preferred text editor and update the “development” and “test” sections with the following values:


development:
  adapter: postgresql
  database: rails_database
  username: rails_user
  password: password
  host: localhost

test:
  adapter: postgresql
  database: rails_database
  username: rails_user
  password: password
  host: localhost

Replace "rails_database", "rails_user", and "password" with the actual values that you used when creating the PostgreSQL user and database. Save the file and exit the editor.

Install the pg gem

After configuring your Ruby on Rails application, we need to install the "pg" gem, which is the PostgreSQL adapter for Ruby. To do this, run the following command in the terminal:


gem install pg

This will install the "pg" gem on your system.

Migrate the database

After installing the "pg" gem, we need to run the database migration to create the necessary tables in the PostgreSQL database. To do this, run the following command in the terminal:


rails db:migrate

This will run the database migration and create the necessary tables in the PostgreSQL database.

By following these steps, you should have successfully configured your Ruby on Rails application to use PostgreSQL on Ubuntu 20.04. You can now use the PostgreSQL database to store and retrieve data in your Ruby on Rails application.