Creating a Ruby on Rails application with a PostgreSQL database

As a lot of us may know, the default database of Ruby on Rails defaults to sqlite3. This is a nice lightweight database to start off with, but doesn’t scale as your project grows. In this article, we’ll discuss how to start a rails application using the Postgres database.

Requirements:

  • Ruby v.2.6.5
  • Rails v.6.0.2.2
  • PostgreSQL v.12.2

Before we begin, we should create a new Postgres database to wire our application with. Let’s open the Postgres interactive terminal and create a database:

postgres=# CREATE DATABASE database_name; 

If all goes well, you should result in an output of CREATE DATABASE
if you would like you can view the database with the \l command.

Next, we should create our Rails application. Before we start lets create a directory to store our application in:

$ mkdir directory_name
$ cd directory_name/

Once inside the directory we can create our new application, specifying that we want Postgres as our database:

$ rails new app_name -d=postgresql

once the app is generated, we’re not quite finished yet, we have to configure our application settings to use the appropriate Postgres database that we created. Navigate to config/database.yml file, and ensure that the database name is correct:

development:
  <<: *default
  database: database_name

Once that is completed save the file and run the server. Navigate to http://localhost:3000/ and you should see that you have a Ruby on Rails application running with a PostgreSQL database.

Congratulations! for more information, please visit my blog section.