Sinatra Heroku PostgreSQL 连接不良

Sinatra Heroku PostgreSQL connection bad

当我尝试从我的 Sinatra 应用程序连接到我的 PostgreSQL 数据库时,我得到 "connection bad"。我正在使用 Heroku 部署应用程序,我的工作站目前是 Windows。我试过了,还是一样的错误信息:

heroku addons:create heroku-postgresql:hobby-dev

来自日志:

PG::ConnectionBad - could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?

来自 config/enviironments.rb:

db = URI.parse(ENV["DATABASE_URL"] || "postgres://localhost")

ActiveRecord::Base.establish_connection(
  :adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
  :host => db.host,
  :username => db.user,
  :password => db.password,
  :database => db.path[1..-1],
  :encoding => 'utf8'
)

这是主要的 app.rb 文件:

require 'sinatra'
require 'haml'
require 'sass/plugin/rack'
require 'pony'
require 'active_record'
require 'pg'
require 'postgresql'
require './vars.rb'
require './includes/functions'
require './config/environments'
Sass::Plugin.options[:style] = :compressed
use Sass::Plugin::Rack
set :haml, :format => :html5
get '/admin' do
  admin_haml :'admin/index'
end
get '/admin/users' do
  admin_haml :'admin/users'
end

这是测试PostgreSQL的函数:

def dbdeb
conn = PG.connect :user => "postgres"
  output = conn.server_version
  conn.close
  return output
end

这是 gemfile:

source 'http://rubygems.org'
ruby '2.2.3'
gem 'sinatra', '1.1.0'
gem 'haml', '4.0.7'
gem 'sass', '3.4.20'
gem 'activerecord','4.2.5'
gem 'sinatra-activerecord'
gem 'pg'
gem 'postgresql'
gem 'pony','1.11'

我做错了什么?

您似乎没有为您的 Heroku 应用程序定义 DATABASE_URL 环境变量。

尝试运行以下命令以查看在您的 Heroku 应用程序上设置了哪些环境变量:

$ heroku config

这应该列出可用的变量。正如您将看到的,没有 DATABASE_URL 变量集。

要设置此变量,您需要创建一个 Heroku Postgres 数据库:

$ heroku addons:create heroku-postgresql:hobby-basic

这将在您的 Heroku 应用程序中创建两个环境变量:

  • DATABASE_URL
  • HEROKU_POSTGRES_COLOR

您可以在 Heroku postgres 文档中找到更多相关信息:https://devcenter.heroku.com/articles/heroku-postgresql#create-a-new-database