Creating Rails App With Postgresql

Wajeeh Ahsan
2 min readJan 29, 2020

--

When you create a new rails app with:

rails new APP_NAME

It creates a new rails app working with sqlite3 as its database. Now, suppose you want to work with postgresql, you’ll have to mention it in the command by using its option ‘-d’ as follow:

rails new APP_NAME --database=postgresql

Now you need to dive into your app directory by running

cd APP_NAME

Now if go to localhost:3000, it will give you an error saying ‘No database error’. This is because you didn’t created your database yet. Now if you run ‘rake dab:create’, it will not work throwing an error
‘ActiveRecord::NoDatabaseError: FATAL: role “YOUR_MACHINE_USERNAME” does not exist’. This happens because you haven’t mentioned your database username in database.yml and hence it takes your machine username as database username.
To resolve this error, dive into postgres shell:

sudo -u postgres psql postgres

where postgres is the default username provided by postgresql by default (with default password as ‘postgres’). Here you will be prompted to enter your root user password (root user of your machine). Now we’re going to change default password (of default ‘postgres’ user). For this, type

\passowrd postgres 

Here, you will be asked to enter new password and then enter it again. Done.
Now, go to your codebase, look for ‘database.yml’ file. Replace this

default: &default
adapter: postgresql
encoding: unicode
username: postgres
password: YOUR_NEW_PASSWROD_FOR_POSTGRES

with

default: &default
adapter: postgresql
encoding: unicode

Now save it and run command

rake db:create

This time DB creation will be successful because we’ve mentioned database username and password. Then run this command

rake db:migrate

Now if you visit ‘localhost:3000’, it will render rails default homepage.

--

--

Wajeeh Ahsan
Wajeeh Ahsan

No responses yet