安装dotenv-rails后Rails无法加载mysql Active Record适配器求助
问题:安装dotenv-rails后触发Active Record适配器加载错误
在新搭建的Rails项目中,原本使用MariaDB(mysql2适配器)一切正常,但安装dotenv-rails后,运行测试或发起请求时都会出现以下错误:
Puma caught this error: Could not load the 'mysql' Active Record adapter. Ensure that the adapter is spelled correctly in config/database.yml and that you've added the necessary adapter gem to your Gemfile. (LoadError) /[...]/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/bootsnap-1.16.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:17:in `require'
即使未实际使用该gem或环境变量,仅安装就会引发问题。已尝试将其移至Gemfile靠前位置等操作,均无效;移除该gem后问题立即消失。当前Gemfile相关部分排序如下:
ruby "3.1.2" gem 'dotenv-rails', require: 'dotenv/rails-now' # <= tried it below as well gem "apipie-rails", "~> 1.2" gem "bootsnap", require: false # Reduces boot times through caching; required in config/boot.rb gem 'mysql2' gem "puma", "~> 5.0" # Use the Puma web server gem "rails", "~> 7.0.7", ">= 7.0.7.2" gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ] # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
解决思路
- 核对database.yml的适配器配置:错误提示找不到
mysql适配器,但你实际使用的是mysql2,检查config/database.yml里的adapter字段是否误写为mysql——dotenv的提前加载可能触发了配置的提前解析,暴露了原本隐藏的拼写问题。 - 调整dotenv加载时机:移除
require: 'dotenv/rails-now'参数,改用默认加载方式,或者把dotenv-rails移到railsgem之后声明。dotenv/rails-now会强制在Rails初始化前加载环境变量,可能干扰了Active Record对适配器gem的加载逻辑。 - 排查bootsnap缓存冲突:bootsnap的路径缓存可能和dotenv的加载机制冲突,临时禁用bootsnap(注释
config/boot.rb里的bootsnap加载代码,或修改Gemfile中bootsnap的require参数),验证问题是否消失。如果有效,清理bootsnap缓存后再重新启用:rm -rf tmp/cache/bootsnap* - 锁定mysql2兼容版本:确认
mysql2gem版本与Rails 7.0.7兼容,尝试在Gemfile中指定兼容版本,比如gem 'mysql2', '~> 0.5.5',然后重新执行bundle install。 - 检查环境变量干扰:dotenv会自动加载项目根目录下的
.env、.env.local等文件,查看这些文件中是否存在DATABASE_URL变量,是否错误地将适配器指定为mysql://而非mysql2://。
内容的提问来源于stack exchange,提问作者dmcblue
相关产品推荐
相关产品推荐

