Create Postgresql database in Heroku with Ruby (without Rails) -


i'm hosting simple ruby script stores urls , scores , saving them yaml. however, i'd save postgresql database instead since yaml file deleted every time restart app. here's error i'm getting in heroku:

could not connect server: no such file or directory (pg::connectionbad) 

here's example script works locally, throws me above error in heroku:

require 'pg' conn = pg.connect( dbname: 'template1' ) res1 = conn.exec('select * pg_database datname = $1', ['words']) if res1.ntuples == 1 # db exists   # 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 top (url, score) values ('http://apple.com', 1);") end 

thanks in advance or suggestions!

assuming have created postgres database using heroku toolchain via heroku addons:add heroku-postgresql:dev (or plan of choice) should have database_url environmental variable contains connection string. can check locally through heroku pg:config.

using pg gem (docs: http://deveiate.org/code/pg/pg/connection.html) - , modifying example there suit -

require 'pg' # source connection string database_url environmental variable conn = pg::connection.new(env['database_url']) res = conn.exec_params('create table top (url varchar, score integer;") 

update: more complete example purposes of error handling:

conn = pg::connection.new(env['test_database_url']) begin     # ensures table created if 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 

Comments