Setting up Rails to use PostgreSQL

A short guide to setting up your Rails project to use the PostgreSQL database

The default database that comes out of the box is Sqlite3 but what if you want to use PostgreSQL?

This is a quick guide on how to configure your Yaml file to allow for PostgreSQL.

First off add the PostgreSQL Gem to your Gemfile.

gem 'pg'

Then navigate to RAILS_ROOT >> config >> database.yml

In here you will want to add your details for PostgreSQL.

default: &default
  adapter: postgresql
  pool: 5 # Specifies the maximum number of connections that can be opened
  timeout: 5000 # in milliseconds. This is how long the app will wait for a database response
  encoding: unicode

development:
  <<: *default # inherits from default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

production:
  <<: *default
  database: myapp

You can set what you want each database to be called and it’s really important that your test database is not called the same as your development or production databases as the test database is wiped clean after each test is ran.

To avoid most of this setup though you can just run the following command when you set up a new Rails project:

rails new myapp --database=postgresql

With this command Rails will put the PostgreSQL Gem into your Gemfile and do a lot of the setup in database.yml for you. Clever old Rails!


Recent posts View all

Ruby

How to ignore Bullet in RSpec tests

Using Bullet during a test can pick up mistakes but also has false negatives; here is an easy way to ignore them

Ruby

How we used Nokogiri to fix a sizing issue in YouTube's oEmbed

At some point, one of our calls to YouTube's oEmbed endpoint was returning videos way too small; we fixed in in our Rails application by using Nokogiri