Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't connect to PostgreSQL database on Heroku using Ruby - could not translate host name

I'm using Ruby (not Rails) and connecting a PostgreSQL database. I've been trying to get set up on Heroku, but I'm having problems starting the application. Running the application locally works fine.

My local .env looks like:

postgres://DATABASE_URL=localhost

And the Ruby connect to connect to the database looks like:

@@db = PGconn.open(:hostaddr => ENV['DATABASE_URL'], :dbname => '(dbname)', :password => '(password)')

When I push to Heroku the app crashes on that line, and writes this error to the logs:

could not translate host name "postgres://(my heroku db address)" to address: Name or service not known (PG::Error)

The database address there matches the DATABASE_URL in my heroku:config. I'm using a shared database.

I tried using :host => ENV['DATABASE_URL'] (as opposed to :hostaddr) but had the same result. I'm guessing there's something simple I'm missing but I haven't had any good ideas.

like image 956
Alex Ghiculescu Avatar asked Jul 08 '12 03:07

Alex Ghiculescu


People also ask

How do I get Heroku Postgres credentials?

To create the credential through data.heroku.com, select the Credentials tab and click the Create Credential button. The name should reflect the purpose of the credential. In the above example, limited_user is used as the credential's username when connecting to the database.


2 Answers

You need to parse out the specific parts of the DATABASE_URL. Please see https://devcenter.heroku.com/articles/rack#database_access

like image 97
Will Avatar answered Sep 30 '22 05:09

Will


Heroku's Devcenter doesn't appear to include this anymore, so here's how to do the split manually:

  db_parts = ENV['DATABASE_URL'].split(/\/|:|@/)
  username = db_parts[3]
  password = db_parts[4]
  host = db_parts[5]
  db = db_parts[7]
  conn = PGconn.open(:host =>  host, :dbname => db, :user=> username, :password=> password)

Courtesy Grio.

like image 35
lambshaanxy Avatar answered Sep 30 '22 04:09

lambshaanxy