If you see it

Live for passion

Switch DB From Sqlite3 to Postgres in Rails App

Switch from sqlite3 to postgres

Step 1: modify Gemfile
1
$ gem 'pg'
Step 2: modify database.yml

Change the database adapter and database name in database.yml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
development:
  adapter: postgresql
  encoding: utf8
  database: inventory_development
  host: localhost
  pool: 5
  timeout: 5000

test:
  adapter: postgresql
  encoding: utf8
  database: inventory_test
  pool: 5
  timeout: 5000

production:
  adapter: postgresql
  encoding: utf8
  database: inventory_production
  pool: 5
  timeout: 5000

Note: You don’t need db/xx in the database part cause postgres is not like sqlite3 provided a file under db folder.

Step 3: create database

You need to create database in postgres based on the name you specified in database.yml, all development, test and production. I used PostgresApp and then:

1
/Applications/Postgres.app/Contents/MacOS/bin/createdb YOUR_DB_NAME

You can follow the documentation and add the bin to your path.

Step 4: Rails DB migrate

Run the following in terminal:

1
2
3
$ bundle update   
$ bundle install  
$ rake db:migrate

IMPORTANT NOTE If you are running your rails server in different mode locally, like production mode, you need to use the following line to performe your db migration.

1
RAILS_ENV=production rake db:migrate
Note

1. If you are planning deploy to heroku, heroku will create the database for you according your database.yml

2. If you are planning deploy to heroku via Snap, you need to go change the configuration for the build to use postgresql manually. Snap will pick up your db choice when you added it to it, but now monitoring it all the time for now.

Comments