Search code examples
rubypostgresqlherokupgheroku-postgres

How can I connect my ruby app to Heroku postgres database?


I have a ruby app running on heroku, I am trying to connect it to a Heroku postgres database. I have installed the add-on and bundled the 'pg' gem. I tried running

PG.connect(dbname:d6td9jdn7irk0u)

Only resulting in this:

PG::ConnectionBad: could not connect to server: No such file or directory. Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

My question is: how can I get the connection established correctly? should I supply the user/password to the connect() function?

Everything I can find when searching online is about people having a similar problem using ruby on rails


Solution

  • Heroku exposes their postgres connection string in DATABASE_URL environment variable. So you just PG.connect(ENV['DATABASE_URL']).

    See https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku#credentials for details.