Error while setting up postgres with rails

Recently while I was setting up postgres with rails using gem 'pg', I got following error -
Postgres version - 9.4

/Library/Ruby/Gems/2.0.0/gems/pg-0.18.4/lib/pg.rb:4:in `require': dlopen(/Library/Ruby/Gems/2.0.0/gems/pg-0.18.4/lib/pg_ext.bundle, 9): Library not loaded: libpq.5.dylib
  Referenced from: /Library/Ruby/Gems/2.0.0/gems/pg-0.18.4/lib/pg_ext.bundle
  Reason: unsafe use of relative rpath libpq.5.dylib in /Library/Ruby/Gems/2.0.0/gems/pg-0.18.4/lib/pg_ext.bundle with restricted binary - /Library/Ruby/Gems/2.0.0/gems/pg-0.18.4/lib/pg_ext.bundle (LoadError)
.............................................................
.............................................................

Following is the reason and fix for the same -

In OS X El Capitan (10.11), Apple added System Integrity Protection. This prevents programs in protected locations like /usr from calling a shared library that uses a relative reference to another shared library. In the case of pg_ext.bundle, it contains a relative reference to the shared library libpq.5.dylib. You can force it to use an absolute reference via the install_name_tool utility. Assuming that libpq.5.dylib is in /Library/PostgreSQL/9.4/lib, run the command

sudo install_name_tool -change libpq.5.dylib \
/Library/PostgreSQL/9.4/lib/libpq.5.dylib \
/Library/Ruby/Gems/2.0.0/gems/pg-0.18.4/lib/pg_ext.bundle

Reference - stackoverflow