You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Homebrew操作导致Rails无法连接PostgreSQL的问题求助

解决Rails无法加载PostgreSQL libpq库的问题

问题现象

在OS X Monterey系统中操作ffmpeg后,Rails/Rake命令启动失败,报错:

dlopen(/Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/pg-1.4.1/lib/pg_ext.bundle, 0x0009): Library not loaded: /opt/homebrew/opt/postgresql/lib/libpq.5.dylib (LoadError)
  Referenced from: /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/pg-1.4.1/lib/pg_ext.bundle
  Reason: tried: '/opt/homebrew/opt/postgresql/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file), '/opt/homebrew/Cellar/postgresql@14/14.5_4/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file) - /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/pg-1.4.1/lib/pg_ext.bundle

执行brew reinstall libpq被中断,提示libpq是keg-only,与postgres formula冲突;按提示重装postgresql@14并重启服务后,问题依旧。psql可正常调用,但Rails无法连接数据库,且/opt/homebrew/opt/postgresql/lib/libpq.5.dylib路径不存在。

解决方案

方法1:重新指定pg gem编译路径

问题根源是pg gem编译时绑定的libpq路径错误,需重新编译pg gem并指定正确的PostgreSQL路径:

  1. 卸载当前pg gem:
gem uninstall pg
  1. 重新安装pg gem,指定postgresql@14的配置路径(替换版本号为报错中对应的pg版本):
gem install pg -v 1.4.1 -- --with-pg-config=/opt/homebrew/opt/postgresql@14/bin/pg_config

方法2:修改动态库引用路径

直接修复pg_ext.bundle中的libpq依赖路径,无需重装gem:

  1. 查看当前pg_ext.bundle的依赖路径:
otool -L /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/pg-1.4.1/lib/pg_ext.bundle
  1. 用install_name_tool替换错误的路径:
install_name_tool -change /opt/homebrew/opt/postgresql/lib/libpq.5.dylib /opt/homebrew/opt/postgresql@14/lib/libpq.5.dylib /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/pg-1.4.1/lib/pg_ext.bundle
  1. 验证路径是否修改成功:
otool -L /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/pg-1.4.1/lib/pg_ext.bundle

方法3:设置临时环境变量

启动Rails前临时指定动态库路径,让系统找到正确的libpq文件:

export DYLD_LIBRARY_PATH=/opt/homebrew/opt/postgresql@14/lib:$DYLD_LIBRARY_PATH
rails s

若需永久生效,可将上述命令添加到shell配置文件(如~/.zshrc或~/.bashrc)中。

内容的提问来源于stack exchange,提问作者Jerome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:51:03