CTAnthny CTAnthny - 3 months ago 23
Ruby Question

Ruby PG gem connection issue

I've searched several related posts for the issue I'm having but wasn't able to find an answer. I'm a student in a coding program where most people use Mac, but I'm on Windows ( 7, Pro, 64 ) - because of that I'm a bit locked in to the tools/software I'll post here.

I'm trying to open a connection through Ruby with the pg gem, and I'm using Sinatra and PostgreSQL. I've established the server, database, and configuration path variables for PostgreSQL, and I've successfully installed pg gem (didn't have an issue there as in some of the other posts) with the line:

gem install pg -- --with-pg-config=C:\Program Files\PostgreSQL\9.5\bin


So the problem is that when I boot up Sinatra and go to the localhost,
I get a NoMethodError, Undefined Method for nil:NilClass on a method that otherwise works for Mac users.

The method is:

configure :development do
set :db_config, { dbname: "news_aggregator_development" }
end

configure :test do
set :db_config, { dbname: "news_aggregator_test" }
end

def db_connection
begin
connection = PG.connect(Sinatra::Application.db_config)
yield(connection)
ensure
connection.close
end
end

get '/articles' do
@results = db_connection do |conn|
conn.exec("SELECT * FROM articles")
end
erb :index
end


connection
returns
nil
, and so the
close
method returns with an undefined method error. I don't think there is a syntax error as I've checked with others regarding this, and I'm thinking it might be related to a connection error with pg.

First time post so please go easy on me =) Apologies if I've left out any needed information - let me know what more context could be helpful and I will try to provide it! Thank you!

mwp mwp
Answer

Two points:

  1. Wrap your Sinatra helpers in a helpers {} block. This will allow you to use settings.db_config instead of Sinatra::Application.db_config:

    helpers do
      def db_connection
        connection = PG.connect(settings.db_config)
        yield connection
      ensure
        connection.close
      end
    end
    
  2. In your PG.connect call, you should pass the host, user, password, and any other options necessary for the pg gem to find, connect, and authenticate to your instance. The dbname alone is not enough—at least not on Windows.

    configure :development do
      set :db_config, {
        host: "localhost",
        port: 5432, 
        user: "foo",
        password: "bar",
        dbname: "news_aggregator_development"
      }
    end
    

Good luck!