Tutorial

How To Set Up Ruby on Rails with Postgres

Updated on June 14, 2022
Default avatar

By Alex Ghiculescu

How To Set Up Ruby on Rails with Postgres

Status: Deprecated

This article is deprecated and no longer maintained.

Reason

We now provide up to date tutorials for using Rails with Postgres that are tailored to individual platforms.

See Instead

This article may still be useful as a reference, but may not work or follow best practices. We strongly recommend using a recent article written for the operating system you are using.

Introduction


Postgres (or PostgreSQL) is an open source database. Ruby on Rails is an open source web framework written in Ruby. Rails is database agnostic, meaning it can be used with a variety of different databases. By default it assumes that MySQL is being used, but it’s quite easy to use with Postgres instead.

This guide will step you through creating a Rails application that uses a Postgres database. You can follow the guide on your local machine or a VPS.

Installing Requirements


Installing Rails using RVM

The easiest way to install Rails is using RVM, which also installs Ruby. To install RVM you will need to ensure your system has curl installed (how you do this depends on your OS). If you already have RVM installed, skip to the next section.

RVM can install Ruby and Rails automatically as part of its installation. To do so, run this command:

\curl -L https://get.rvm.io | bash -s stable --rails

Note: you should review the RVM install script before running it (or any other remote script that you pipe into bash.

RVM will install itself on your system. You can now use it to manage your Ruby versions. This is useful as you may require different versions of Ruby for different projects. RVM also installed the Rails gem for us.

Installing Rails using RubyGems

If you already have RVM installed, you don’t need to re-install it. Instead you can simply install Rails by installing the gem:

gem install rails

This will install Rails and any other gems it requires.

Installing Postgres

The method of installing Postgres depends on your OS. See postgresql.org/download for a full list. Generally it’s easiest to use a package manager such as apt-get on Ubuntu or Homebrew on OS X.

If you are installing Postgres on a local machine you may also want to install a GUI (though this guide assumes command line usage). pgAdmin isn’t the prettiest tool in the world, but it does the job.

Finally, you’ll want to install the pg gem so that you can interface with Postgres from Ruby code. To do so:

gem install pg

Setting Up Postgres


Create a Postgres user for the Rails app we’ll create in the next step. To do this, switch into the Postgres user:

su - postgres

After that access Postgres:

psql

Then create a user (or a “role”, as Postgres calls it):

create role myapp with createdb login password 'password1';

Creating Your Rails App


To create a Rails app configured for Postgres, run this command:

rails new myapp --database=postgresql

This creates a directory called “myapp” which houses an app called “myapp” (you can name it anything you like when running the command). Rails expects the name of the database user to match the name of the application, but you can easily change that if need be.

We will now configure which database Rails will talk to. This is done using the database.yml file, located at:

RAILS_ROOT/config/database.yml

Note: RAILS_ROOT is the Rails root directory. In the above example, it would be at /myapp (relative to your current location).

The database.yml file is used by Rails to connect to the appropriate database for the current Rails environment. It uses YAML, a data serialization standard. There are a few databases listed here for different environments; development, test, and production. By default Rails will expect a different database for each environment. This is handy because, for example, the test database is emptied and rebuilt every time you run Rails tests. For each database, ensure that the username and password match the username and password you gave your Postgres user.

Once configured, your database.yml should contain something like this:

development:
  adapter: postgresql
  encoding: unicode
  database: myapp_development
  pool: 5
  username: myapp
  password: password1

test:
  adapter: postgresql
  encoding: unicode
  database: myapp_test
  pool: 5
  username: myapp
  password: password1

You can then run:

rake db:setup

This will create development and test databases, set their owners to the user specified, and create “schema_migrations” tables in each. This table is used to record your migrations to schemas and data.

Running Rails


You should be able to start your Rails app now:

rails server

If you navigate to localhost:3000 you should see a Rails landing page. This doesn’t really do much though. To interact with our database, let’s create a scaffold:

rails g scaffold Post title:string body:text
rake db:migrate

Now navigate to localhost:3000/posts. From here, you can create new posts, edit existing posts, and delete posts. See the Rails getting started guide for more introductory operations.

Your Rails app is now talking to a Postgres database!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alex Ghiculescu

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Please a one click installer with RoR and Postgres

also dont forget to specify your host , your yml defaults should look something like this – may be

default: &default adapter: postgresql encoding: unicode username: testapp password: <%= ENV[‘YOURAPP_DATABASE_PASSWORD’] %>

Add your apps password to ~./bashrc file

For details on connection pooling, see rails configuration guide

http://guides.rubyonrails.org/configuring.html#database-pooling

pool: 5 host: localhost

There is a step missing in the above Setting Up Postgres Create a Postgres user for the Rails app we’ll create in the next step. To do this, switch into the Postgres user: su - postgres Then create a user (or a “role”, as Postgres calls it): # this is where the missing step should be create role myapp with createdb login password ‘password1’ The missing step is psql Then you can enter “create role myapp with createdb login password ‘password1’” sucessfully

Ugh, I keep getting this error when using rake db:setup. I also tried rake db:migrate. And lastly bundle exec rake db:create. For all I get this error:

rake aborted! database configuration does not specify adapter

I even tried deleted the rails files and putting them into a different directory under /home/rails/ I’ve searched the Internet. I also tried editing my database.yml file several times to no avail.

Any idea what is causing the adapter problem? I have this in my database.yml:

production: adapter: postgresql encoding: unicode database: acsjvl_production username: acsjvl password: ######

Help! Thank you!

This did not work for me.

I needed to add this line to database.yml for both test and dev db’s : host: localhost

This tutorial helped me a bit but it also took me many hours to figure out stuff it doesn’t explain. For example, when setting up the database configuration and then using rake db:setup, it’s using peer authentication, so it’s expecting a user named myapp to connect to the database, not my username or postgres. To fix it I had to create a new user myapp and build the app elsewhere (because I didn’t have permission to edit the apps created by other users).

It also doesn’t explain that the “create role…” command should happen inside psql (postgres);

https://www.codementor.io/engineerapart/getting-started-with-postgresql-on-mac-osx-are8jcopb

Thanks! Solved my database errors with this article in combination with ^ this. For those getting permission errors, see above

On a freshly provisioned server with postgresql, the pg_hba.conf file probably needs to be reconfigured. At the line containing:

local   all             all                                     peer

change peer to md5. Make sure to restart the postgresql server after this.

Changing this allows your roles to work as expected.

Hi, I was just wondering if anyone knows where the posts that are created are stored? Where is local file?

Thanks

So many people don’t know that there is a gem to perform all the stuff with just one command

https://github.com/sandrew/from-scratch

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel