How to Use Postgres with Ruby on Rails

Sam Evans
2 min readOct 2, 2020

Ruby on Rails, an open source web framework, uses SQLite has the default database, but it is not the only sql database available! PostgreSQL (or Postgres) is an open source database with just a few more features available to you.

Installation

Rails

If you have found yourself here, I assumed you already have Ruby installed. Install rails with:

gem install rails

This will globally install rails and all of its dependencies.

Postgres

Installing Postgres is a little different for each OS, and the documentation can be found here:

https://www.postgresql.org/download/

Follow this up by installing the Postgres gem that will allow you to work with Postgres from your Ruby code.

gem install pg

This is where Postgres starts to divert from from SQLite. SQLite is a server-less database that runs as part of the app. Postgres, on the other hand is implemented as a server process, where your app communicates with the Postgres server. You can read in depth about these and other differences here:

Setup

First, you need to make sure your Postgres database server is running. This can be done a few different ways, with different options for different OS. Refer to

https://www.postgresql.org/docs/9.1/server-start.html

Then you must create a Postgres user for your app. To do this, open the Postgres command line tool with :

psql postgres

Then:

create role {app_name} with createdb login password '{some_password}';

This sets up a Postgres ‘role’ (read: user) that has permission to create a database.

Rails

Next, you will create your Rails api with with just a slight change from the command you might be used to:

rails new {app_name} --api --database=postgresql

Keep in mind, Rails will expect that the name of your app is exactly the same as the name of the Postgres role you just created. You can change this later, if necessary, but the two should always be the same.

Now, navigate to the Rails root directory for your app, and find the database.yml file:

.../{app_name}/config/database.yml

This file is used to connect your Rails api to Postgres through the role you created. It will have several different databases listed, all used for different environments (Production, Development, Testing, etc…). You will need to configure it something like this, with different headers and different specific database names for each environment.

development:
adapter: postgresql
encoding: unicode
database: app_name_development
pool: 5
username: app_name
password: some_password

Now you can run your Rails migrations just like you would have with SQLite!

--

--