PostgreSQL Setup - thuy-econsys/rails_app GitHub Wiki

Setup environment variable for designating location of the PostgreSQL data directory. Note that the location of this directory is specific to MacOSX:

$ echo 'export PGDATA=/usr/local/var/postgres' >> ~/.bash_profile

Initialize database. This needs to be performed only once to establish the database system. There will be an error stating that your data directory already "exists but is not empty" if you run this again:

$ initdb

Start PostgreSQL server. Option -l designates the file path for the log file, which is optional. An option -D which designates location of data directory is normally required but since we have already established the PGDATA environment variable above, this is no longer necessary:

$ pg_ctl start -l /usr/local/var/log/postgres.log

Login to the PostgreSQL client and create a Postgres user role which has privileges of being able to create a database (CREATEDB), ensure user logs in (LOGIN), with a password (PASSWORD). Replace <user_name> and <password> with your own username and password, respectively. Be sure to remove the brackets but keep the single quotes for the password:

$ sudo -u postgres psql

postgres=# CREATE ROLE <user_name> WITH CREATEDB LOGIN PASSWORD '<password>';
CREATE ROLE

Setup environment variables that will be used in /config/database.yml as well as for logging into psql client. Replace <user_name> and <password> with the username and password setup in psql client.:

$ cat << EOF >> ~/.bash_profile
> export PG_USERNAME=<user_name>
> export PG_PASSWORD=<password>
> export PG_DBNAME=<db_name>
> export PG_HOST=localhost
> export PG_PORT=5432
> EOF

Install PostgreSQL gem to your Rails project. Inside the Rails directory:

$ gem install pg
...
$ bundle install

Setup /config/database.yml to use the PostgreSQL environment variables

  adapter: postgresql
  encoding: unicode
  pool:     <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: <%= ENV["PG_USERNAME"] %>
  password: <%= ENV["PG_PASSWORD"] %>
  host:     <%= ENV["PG_HOST"] %>
  port:     <%= ENV["PG_PORT"] %>

development:
  <<: *default
  database: <%= ENV["PG_DBNAME"] || 'rails_app_development' %>

test:
  <<: *default
  database: rails_app_test

production:
  <<: *default
  database: rails_app_production

Login to the psql client with the PostgreSQL environment variables and run \conninfo inside the psql client to confirm your connection details:

$ psql -h $PG_HOST -U $PG_USERNAME -p $PG_PORT $PG_DBNAME
psql (12.4)
Type "help" for help.

rails_app_development=> \conninfo
You are connected to database "rails_app_development" as user "<user_name>" on host "localhost" (address "::1") at port "5432".

##References

⚠️ **GitHub.com Fallback** ⚠️