Search code examples
ruby-on-railspostgresqlactiverecordpassengerrbenv

ActiveRecord attempting to connect to the wrong database using rbenv


Getting an error in /log/production.log when performing get request on site root:

I, [2016-03-21T02:21:38.485274 #12750]  INFO -- :
    Started GET "/" for 174.xx.xxx.xxx at 2016-03-21 02:21:38 -0600
F, [2016-03-21T02:21:38.493250 #12750] FATAL -- :
    ActiveRecord::NoDatabaseError (FATAL:  database "y" does not exist)

It says database "y" does not exist. First off, y is not a database, so I know it doesn't exist.

Secondly, database.yml specifies ydb as the database that the app should connect to - not y.

config/database.yml:

production:
  adapter: postgresql
  encoding: utf8
  host: <%= ENV['Y_PG_HOST'] %>
  database: <%= ENV['Y_PG_DB'] %>
  username: <%= ENV['Y_PG_USER'] %>
  password: <%= ENV['Y_PG_PASS'] %>

Using rbenv to declare the env vars:

.rbenv-vars

  Y_PG_HOST=localhost
  Y_PG_DB=ydb
  Y_PG_USER=y
  Y_PG_PASS=*********

Update

Thanks to @Meshpi, it appears that rbenv is where the issue is occurring. When the env vars are placed directly in database.yml, the server loads the site as expected.

What is puzzling is that from echo $Y_PG_DB, the shell returns ydb, not y.


Solution

  • Development worked fine. Even rails console production on the server worked with app.get '/' with no database errors. However, when putting the request through the browser, all hell broke loose.

    The problem is that the instructions that Phusion Passenger gives at the end of its installation are not exactly compatible with rbenv-vars.

    At the end of the Passenger installation, you are instructed to add the following to nginx.conf:

    passenger_root /home/user/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/passenger-5.0.26;
    passenger_ruby /home/user/.rbenv/versions/2.3.0/bin/ruby;
    

    However, then as @mislav pointed out, the Ruby scripts would be spinning up the ruby processes directly instead of through rbenv.

    To fix this, what needs to be in nginx.conf instead is:

    passenger_root /home/user/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/passenger-5.0.26;
    passenger_ruby /home/user/.rbenv/shims/ruby;
    

    Hope this helps spare another unsuspecting soul :D