How to configure rails app so that local development and production deploys both working

I was coding my rails app with sqlite3 and all was fine.

Then I deployed to Heroku and had to change DB to Postgres. The only way I could get production deploy to work is by just having gem pg in the gem file, as opposed to have it in a :production group.

Anyway, when I try to configure app the following way,the app won't run locally anymore. What am I missing?

Gem File

group :development do
  gem 'web-console', '>= 3.3.0'
  gem 'sqlite3'
end

group :production do
 gem 'pg'
end

and here's my db.yml file

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  adapter: postgresql
  database: db/production.sqlite3

2 answers

  • answered 2020-07-11 17:18 praaveen

    Production, it is working because of pg gem and postgresql adapter

    database.yml

    default: &default
      adapter: postgresql
    
    production:
      <<: *default
      adapter: postgresql
    

    gem file

    group :production do
     gem 'pg'
    end
    

    In development it fails because of sqlite3 gem and postgresql adapter. Add right database gem. If postgresql then, gem 'pg' inside development group

    database.yml

    default: &default
      adapter: postgresql
      
    
    development:
      <<: *default
      database: dev-database
    

    gem file

    group :development do
      gem 'web-console', '>= 3.3.0'
      gem 'pg'
    end
    

    Better switch to a single database.

    This link may help to choose the right DB based on your requirement. Sqlite3 vs Postgres vs Mysql - Rails

  • answered 2020-07-11 21:32 rmlockerd

    @praaveen's answer is absolutely correct, but just to expand slightly since his snippet of database.yml was just a relevant subset, not complete. In config/database.yml you specify the database configuration for each environment (dev, test, prod). That configuration does vary by the type of database as well, and specifically when moving from Sqlite3 to Postgres you need to change the database names, and add the username and password for each environment. So, the database.yml should look something like:

    default: &default
      adapter: postgresql
      pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
    
    development:
      <<: *default
      database: dev-database
      username: whatever
      password: whatever
    
    test:
    ... etc etc
    

    Here's a blog article that covers what you need to change to switch from sqlite to Postgres in an existing project in more step-by-step fashion. Also note since you are using Heroku for production, the specification of database settings works a bit differently. See this for a description of how Heroku PG configuration works.