我如何在 heroku 中连接我的 postgres 数据库?

How do i connect my postgres db in heroku?

我正在学习 Rack,并且我构建了一个测试待办事项应用程序。我的测试应用程序使用 postgres 数据库。我正在尝试将我的应用程序部署到 heroku 免费帐户。

Currenlty 我正在尝试使用此连接到 postgres

DB = PG.connect :hostaddr => "localhost", :port => 5432, :dbname => 'testdb', :user => "postgres", :password => "postgres"

我检查了我的日志,因为当我访问 url 并发现

时我的应用程序无法运行
2017-06-01T13:22:35.540907+00:00 app[web.1]: Puma starting in single mode...
2017-06-01T13:22:35.540929+00:00 app[web.1]: * Version 3.8.2 (ruby 2.3.4-p301), codename: Sassy Salamander
2017-06-01T13:22:35.540930+00:00 app[web.1]: * Min threads: 5, max threads: 5
2017-06-01T13:22:35.540975+00:00 app[web.1]: * Environment: production
2017-06-01T13:22:35.583653+00:00 app[web.1]: ! Unable to load application: PG::ConnectionBad: could not connect to server: Connection refused
2017-06-01T13:22:35.583655+00:00 app[web.1]:    Is the server running on host "127.0.0.1" and accepting
2017-06-01T13:22:35.583656+00:00 app[web.1]:    TCP/IP connections on port 5432?
2017-06-01T13:22:35.583775+00:00 app[web.1]: bundler: failed to load command: puma (/app/vendor/bundle/ruby/2.3.0/bin/puma)
2017-06-01T13:22:35.583838+00:00 app[web.1]: PG::ConnectionBad: could not connect to server: Connection refused
2017-06-01T13:22:35.583839+00:00 app[web.1]:    Is the server running on host "127.0.0.1" and accepting
2017-06-01T13:22:35.583840+00:00 app[web.1]:    TCP/IP connections on port 5432?

编辑 1

我在 heroku 中找到了 postgres db creds 并使用了它并得到了这个错误

2017-06-01T14:27:11.889525+00:00 app[web.1]: Puma starting in single mode...
2017-06-01T14:27:11.889599+00:00 app[web.1]: * Version 3.8.2 (ruby 2.3.4-p301), codename: Sassy Salamander
2017-06-01T14:27:11.889633+00:00 app[web.1]: * Min threads: 5, max threads: 5
2017-06-01T14:27:11.889671+00:00 app[web.1]: * Environment: production
2017-06-01T14:27:11.934347+00:00 app[web.1]: ! Unable to load application: PG::ConnectionBad: could not translate host name "ec2-23-23-234-118.compute-1.amazonaws.com" to address: Name or service not known
2017-06-01T14:27:11.934473+00:00 app[web.1]: bundler: failed to load command: puma (/app/vendor/bundle/ruby/2.3.0/bin/puma)
2017-06-01T14:27:11.934522+00:00 app[web.1]: PG::ConnectionBad: could not translate host name "ec2-23-23-234-118.compute-1.amazonaws.com" to address: Name or service not known

您可以从 DATABASE_URL 环境变量获取 Heroku 上的数据库配置:

ENV['DATABASE_URL']

这是一个连接 URL,看起来像这样:

postgres://$user:$pass@$db_host.com:5432/$db_name

您可以将该字符串直接传递给您的 PG 客户端初始化程序:

DB = PG.connect ENV['DATABASE_URL']

DB 现在是您连接的数据库客户端。

用这个解决了DB = PG.connect ENV["HEROKU_POSTGRESQL_SILVER_URL"]