使用Ruby在Heroku中创建Postgresql数据库(不带Rails)

时间:2015-07-15 03:31:08

标签: ruby postgresql heroku

我目前正在托管一个简单的Ruby脚本,用于存储URL和分数并将其保存到YAML。但是,我想保存到Postgresql数据库,因为每次重新启动应用程序时都会删除yaml文件。这是我在Heroku中遇到的错误:

could not connect to server: No such file or directory (PG::ConnectionBad)

这是一个在本地工作的示例脚本,但在Heroku中抛出了上述错误:

require 'pg'
conn = PG.connect( dbname: 'template1' )
res1 = conn.exec('SELECT * from pg_database where datname = $1', ['words'])
if res1.ntuples == 1 # db exists
  # do nothing
else
  conn.exec('CREATE DATABASE words')
  words_conn = PGconn.connect( :dbname => 'words')
  words_conn.exec("create table top (url varchar, score integer);")
  words_conn.exec("INSERT INTO top (url, score) VALUES ('http://apple.com', 1);")
end

提前感谢您的任何帮助或建议!

1 个答案:

答案 0 :(得分:1)

假设您已经使用Heroku工具链通过heroku addons:add heroku-postgresql:dev(或您选择的计划)创建了Postgres数据库,那么您应该拥有一个包含连接字符串的DATABASE_URL环境变量。您可以通过heroku pg:config在本地查看。

使用pg gem(文档:http://deveiate.org/code/pg/PG/Connection.html) - 并从那里修改示例以适应 -

require 'pg'
# source the connection string from the DATABASE_URL environmental variable
conn = PG::Connection.new(ENV['DATABASE_URL'])
res = conn.exec_params('create table top (url varchar, score integer;")

更新:出于错误处理的目的,这是一个稍微完整的示例:

conn = PG::Connection.new(ENV['TEST_DATABASE_URL'])
begin
    # Ensures the table is created if it doesn't exist
    res = conn.exec("CREATE TABLE IF NOT EXISTS top (url varchar, score integer);")
    res.result_status
rescue PG::Error => pg_error
    puts "Table creation failed: #{pg_error.message}"
end
相关问题