Skip to content

# Step 02 — Setting Up the Database

Gerald Goh edited this page Sep 8, 2020 · 2 revisions

Setup Rail's linkage by editing database.yml as below

# config/database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  adapter: postgresql
  encoding: unicode
  database: energy_tracker_development
  username: postgres
  password: postgres
  host: 127.0.0.1

test:
  adapter: postgresql
  encoding: unicode
  database: energy_tracker_test
  username: postgres
  password: postgres
  host: 127.0.0.1

production:
  adapter: postgresql
  encoding: unicode
  database: energy_tracker_production
  username: postgres
  password: postgres
  host: 127.0.0.1

(OPTION#1) DB setup with docker

Open terminal and type the following command

docker run -d --name energy-tracker -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -d -p 5432:5432 postgres

Additional useful docker commands

List containers with commands below;
$ docker container ls -a

# Start certain container
$ docker start <container ID>

# Stop specific container
$ docker stop <container>

# Remote inactive containers
$ docker container prune -a

# Remove containers
$ docker rm <container ID>

# Remove images
$ docker rmi <image ID>

# Delete volumes
$ docker volume rm <volume ID>

(OPTION#2) DB setup with Linux

Open terminal and type the following command

sudo -u postgres createuser -s railsdevuser
sudo -u postgres psql
postgres=# \password railsdevuser
Enter new password:
Enter it again:
\q

Rails DB setup

$ rails db:create

Created database 'energy_tracker_development'
Created database 'energy_tracker_test

Start Application

To test Rails is connected to newly create DB

rails s --binding=127.0.0.1

=> Booting Puma
=> Rails 6.0.2.2 application starting in development
=> Run `rails server --help` for more startup options
Puma starting in single mode...
* Version 4.3.3 (ruby 2.6.5-p114), codename: Mysterious Traveller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://127.0.0.1:3000
Use Ctrl-C to stop
Started GET "/" for 127.0.0.1 at 2020-04-28 00:19:10 +0800
Processing by Rails::WelcomeController#index as HTML
  Rendering /home/user/.rvm/gems/ruby-2.6.5/gems/railties-6.0.2.2/lib/rails/templates/rails/welcome/index.html.erb
  Rendered /home/user/.rvm/gems/ruby-2.6.5/gems/railties-6.0.2.2/lib/rails/templates/rails/welcome/index.html.erb (Duration: 11.0ms | Allocations: 471)
Completed 200 OK in 37ms (Views: 21.9ms | ActiveRecord: 0.0ms | Allocations: 2793)