如何将我的 ruby 应用程序连接到 Heroku postgres 数据库?

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

我在 heroku 上有一个 ruby 应用程序 运行,我正在尝试将它连接到 Heroku postgres 数据库。我已经安装了附加组件并捆绑了 'pg' gem。我试过了 运行

PG.connect(dbname:d6td9jdn7irk0u)

只会导致这个:

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"?

我的问题是:我怎样才能正确建立连接?我应该将 user/password 提供给 connect() 函数吗?

我在网上搜索时能找到的所有内容都是关于在 rails

上使用 ruby 遇到类似问题的人

有点解决了。 PG.connect() 采用可以包含 host/port/user/password 信息的散列。所有这些信息都可以使用以下命令从 heroku cli 中检索:

heroku pg:credentials:url database

不幸的是,数据库凭据不是永久的。因此,每次部署时,我都必须确保应用已成功部署。

Heroku 在 DATABASE_URL 环境变量中公开了他们的 postgres 连接字符串。所以你只是 PG.connect(ENV['DATABASE_URL']).

详情见https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku#credentials