Installing pg gem with the Postgres.app

When working on MacOS you have the great advantage of using Postgres.app "The easiest way to get started with PostgreSQL on the Mac". But if you are working with Rails, the moment you do a bundle install you will encounter with this error:

Installing pg 0.18.3 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    /Users/jorgecaballero/.rvm/rubies/ruby-2.1.1/bin/ruby extconf.rb
checking for pg_config... no  
No pg_config... trying anyway. If building fails, please try again with  
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no  
Can't find the 'libpq-fe.h header  
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary  
libraries and/or headers.  Check the mkmf.log file for more details.  You may  
need configuration options.

Provided configuration options:  
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/Users/jorgecaballero/.rvm/rubies/ruby-2.1.1/bin/ruby
    --with-pg
    --without-pg
    --enable-windows-cross
    --disable-windows-cross
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib

extconf failed, exit code 1

Gem files will remain installed in /Users/jorgecaballero/.rvm/gems/ruby-2.1.1/gems/pg-0.18.3 for inspection.  
Results logged to /Users/jorgecaballero/.rvm/gems/ruby-2.1.1/extensions/x86_64-darwin-12/2.1.0-static/pg-0.18.3/gem_make.out  
An error occurred while installing pg (0.18.3), and Bundler cannot continue.  
Make sure that `gem install pg -v '0.18.3'` succeeds before bundling.  

This happens because the bundler can't find the pg's bins. To correct this issue you have to install the gem with the flag --with-pg-config. Your Postgres app contains all the info necessary to install the gem. Generally the pg_config can be found under /Applications/Postgres.app/Contents/Versions/9.x/bin/pg_config. Replace the x with the version installed in your computer.

Finally run gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.6/bin/pg_config and you will get the following result:

Building native extensions with: '--with-pg-config=/Applications/Postgres.app/Contents/Versions/9.3/bin/pg_config'  
This could take a while...  
Successfully installed pg-0.18.3  
invalid options: -f fivefish  
(invalid options are ignored)
Parsing documentation for pg-0.18.3  
Installing ri documentation for pg-0.18.3  
Done installing documentation for pg after 3 seconds  
1 gem installed  

That's all.

Cover image by Rowan Heuvel

Jorge Caballero

Read more posts by this author.