This is a summary of the steps to change the database of a new project created with Ruby on Rails.
The standard database for Ruby on Rails is  SQLite3 </ b>, but when deploying to  Heroku, SQLite3 gives an error. </ b>
If you change to PostgreSQL at the time of rails new, you can save the trouble of migrating data later.
First install the xcode required to install Homebrew.
xcode-select --install
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
Click here for the official page: Homebrew
You can download the latest stable version by specifying postgresql.
brew install postgresql
Update .bash_profile
ECHO 'export PGDATA=/usr/local/var/postgres' >> .bash_profile
Reload .bash_profile
source ~/.bash_profile
Create a user to manage the database.
 createuser <username>
Update the Gemfile and change the description of SQLite3 to PostgreSQL.
Change before
Gemfile.rb
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~> 1.4'
After change
Gemfile.rb
# Use Postgres as the database for Active Record
gem 'pg'
Install the gem with bundle install.
bundle install
app/config/database.yml
 default: &default
   adapter: postgresql
   encoding: unicode
   pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
   timeout: 5000
 development:
   <<: *default
   database: myapp_dev #Arbitrary database name
 test:
   <<: *default
   database: myapp_sandbox #Arbitrary database name
 production:
   <<: *default
   database: myapp_production #Arbitrary database name
   username: <username> #Any username
   password: request.env['DB_PASSWORD'] #Any password
   adapter: postgresql
   encoding: unicode
   pool:  <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
If you write the password as it is in database.yml, the password will be exposed when you update it on GitHub with Public.
Create a .env file to manage your environment variables.
Add the .env file to .gitignore to prevent it from being uploaded to GitHub.
.env
DB_PASSWORD = '<password>'
.gitignore
.env
bundle exec rails db:create
If the following message appears, PostgreSQL has completed the database creation.
Created database 'myapp_dev'
Created database 'myapp_sandbox'
        Recommended Posts