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

Rails应用迁移至Heroku失败:postgresql数据库适配器加载错误

解决Gem::LoadError: Specified 'postgresql' for database adapter, but the gem is not loaded问题

问题重现

你碰到的错误信息如下:

rake aborted! Gem::LoadError: Specified 'postgresql' for database adapter, but the gem is not loaded. Add `gem 'pg'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).

你的Gemfile配置:

group :production do 
  gem 'pg', '~> 0.18.4' 
  gem 'rails_12factor', '~> 0.0.3' 
end

并且你已经执行了 bundle install --without production,但错误依旧存在。

问题根源

核心原因很直白:你把pg gem仅放在了production环境组里,却用--without production跳过了该组的gem安装,同时你的数据库配置文件(config/database.yml)里指定了adapter: postgresql——本地环境找不到pg gem,自然就抛出了加载错误。

解决方案

根据你的实际使用场景,任选以下一种方法即可:

1. 本地开发也使用PostgreSQL(推荐)

把pg gem移出production组,让所有环境都能加载,或者同时添加到development和test组:

# 方案A:所有环境共享pg gem
gem 'pg', '~> 0.18.4'

group :production do 
  gem 'rails_12factor', '~> 0.0.3' 
end

# 方案B:仅在开发、测试、生产环境加载pg
group :development, :test, :production do
  gem 'pg', '~> 0.18.4'
end

group :production do 
  gem 'rails_12factor', '~> 0.0.3' 
end

修改后重新执行:

bundle install

2. 本地用SQLite3,生产环境用PostgreSQL

如果本地不想安装PostgreSQL,只需修改config/database.yml中development和test部分的adapter为sqlite3,同时确保Gemfile里包含sqlite3依赖:

# 在Gemfile中添加sqlite3到开发测试组
group :development, :test do
  gem 'sqlite3'
end

group :production do 
  gem 'pg', '~> 0.18.4' 
  gem 'rails_12factor', '~> 0.0.3' 
end

然后执行:

bundle install --without production

3. 临时加载production组的gem(特殊场景用)

如果你确实需要在本地环境加载production组的依赖,重新执行bundle安装时不要跳过该组:

# 清除之前的without配置(如果有的话)
bundle config unset without
# 重新安装所有依赖
bundle install

验证

完成上述步骤后,再运行你的rake命令(比如rake db:migrate),应该就能正常执行了。

内容的提问来源于stack exchange,提问作者Rony M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:12:45