How to use PostgreSQL with your Ruby on Rails application on Ubuntu 16.04
Learn how to use PostgreSQL with your Ruby on Rails application, instead of the default SQLite database. SQLite is an easy-to-configure, lightweight product which ships with Ruby on Rails by default. However, PostgreSQL is a more robust solution which provides more advanced features, scaling, and stability, which may make it more suitable for your Ruby on Rails project.
Requirements
- A Cloud Server running Linux (Ubuntu 16.04)
- PostgreSQL installed and running.
- Ruby on Rails installed and running.
- A basic familiarity with Ruby on Rails.
All of the commands in this tutorial must be issued as the Rails user. This is the user account which you used to install and run Ruby on Rails.
Create a PostgreSQL user
Create a PostgreSQL user so that your Ruby on Rails application will be able to connect to the PostgreSQL database:
This should be the same username which you used to install and run Ruby on Rails.
For example, to create the PostgreSQL username jdoe the command is:
To set a password for this user, log in to the PostgreSQL command line client:
At the PostgreSQL prompt, enter the following command to set the password:
For example, to set the password for jdoe the command is:
Enter and confirm the password. Then exit the PostgreSQL client:
- Unlimited traffic
- Fast SSD NVMe storage
- Free Plesk Web Host Edition
Configure the Rails Application
The next step is to enable PostgreSQL support in your Ruby on Rails application.
Create the Application
First, create the application using the -d postgresql flag:
For example, the command to create an application named my-app is:
The -d flag tells Ruby on Rails that you will be using PostgreSQL for this application.
Add the PostgreSQL username and password
Next, move into the directory which Ruby on Rails created for the application:
Edit the config/database.yml file:
Scroll down to the section which reads:
Delete the # in the last line to un-comment it, and change the username to the one you created:
In the next section, delete the # to un-comment the last line, and add the password for the jdoe user:
Save and exit the file.
Create the new application databases
Use the following rake command to create the databases for your application:
Test the configuration
To test the configuration, simply start the rails application and check it in a browser.
From the application's directory, use the command:
Binding the server to 0.0.0.0 allows you to view the application using your server's public IP address.
The server should respond with:
Switch to a browser and visit "http://your-ip-address:3000". For example, if your IP address is 198.162.0.1 you would go to http://198.162.0:3000.
If all is well and Rails is able to connect to PostgreSQL, you will see the default Rails welcome page.