In my previous Ubuntu install Rails post, I had installed Ruby on Rails environment in Ubuntu 18.04 but utilizing SQLite. Now I am trying to connect Ruby on Rails to PostgreSQL. To install PostgreSQL, refer to my Ubuntu install PostgreSQL post.
Firstly, we need to install PostgreSQL gem and log in as postgres user.
gem install pg
sudo su - postgres
Create a role
From within PostgreSQL, run the command below to create a new role. The du command to check the newly created role and q to quit the PostgreSQL prompt. Lastly exit the postgres user back to ubuntu user.
create role blog with createdb login password 'password1';
Create a project
Now we will create a project called “blog” and have it connect to the PostgreSQL database. Let’s reuse the same project folder structure from my previous Ubuntu install Rails post.
rails new blog --database=postgresql
Setup a new database
Run the command below after successfully configure your database.yml file.
Create CRUD scaffold
Create a scaffold with CRUD (create, read, update, delete) to see if you are able to store into the PostgreSQL database.
rails g scaffold Post title:string body:text
Next add user postgres to sudo group and change user to postgres.
sudo usermod -a -G sudo postgres
sudo su - postgres
Now run psql command, change the password for postgres and quit.
Connecting to PostgreSQL with pgAdmin through SSH tunnel
I assume you have pgAdmin installed. To connect, click add new server and refer to the screenshots below.
Once click [Save]. You will be connected to your PostgreSQL database.
Connecting to PostgreSQL with pgAdmin directly
PostgreSQL by default is not listening to external connections. You’ll need to allow remote connections. To do that, change user to root and edit the configuration file. Your configuration file path might differ from mine depending on which version of Postgres you install. Mine is version 10.