Open In App

How to Implement PostgreSQL Database in Rails Application?

Last Updated : 12 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to look into the implementation of PostgreSQL in a rails application. As we know that database is a very important part of any web application that’s why today modern web applications like Flipkart, Amazon, Netflix all the websites are use database.

Before going forward we need to know a little about what is the database and also what is PostgreSQL database.

Database: It is just like software that is used to manage data. Like insert new data, delete existing data, update existing data, and more. There are two types of database relational database and non-relational database.

PostgreSQL: PostgreSQL is a relational database in which the database data is store in tabular format means row and column manner. PostgreSQL, also known as Postgres, is a free and open-source relational database management system.

Prerequisites:

Implementation:

After installing all prerequisite items you have to create new rails app. To do so use the below commands:

$ rails new my_postgresql_app
$ cd my_postgresql_app

Now you have to open the my_postgresql_app project any IDE and move config/database.yml and you will see that by default rails application support sqlite3  database, but rails also support different type database like PostgreSQL , MySQL etc. 

So to add PostgreSQL database in rails application we will have to add pg gem in our project Gemfile file and remove gem ‘sqlite3’, ‘~> 1.4’  from gemfile.

gem 'pg'

 After adding pg gem in gemfile run given command on terminal.

$ bundle install

This command installs all necessary files for implement the PostgreSQL database.

Next, we have to move on the config/database.yml file and remove all existing data from this file and add new data for connecting to PostgreSQL.

development:
  adapter: postgresql
  encoding: unicode
  database: database_name_development
  pool: 5
  host: localhost
  username: postgres_user_name
  password: postgres_password

test:
  adapter: postgresql
  encoding: unicode
  database: database_name_test
  pool: 5
  username: postgres_user_name
  password: postgres_password

staging:
  url: <%= ENV['DATABASE_URL'] %>

production:
  url: <%= ENV['DATABASE_URL'] %> 

After adding the data in config/database.yml file you have to run the given command.

$ rails db:create

Now you successfully connect your rails application with the PostgreSQL database.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads