Rails项目内执行rails命令报错(bootsnap加载失败)求助
Rails项目内执行
rails命令报错求助 问题现象
在非Rails项目目录执行rails --version一切正常,但进入项目目录后,任何rails命令都无法运行。执行rails -v时出现如下错误:
❯ rails -v /Users/mac/Devs/Rails/test/rails-test-api/config/boot.rb:4:in `require': cannot load such file -- bootsnap/setup (LoadError) from /Users/mac/Devs/Rails/test/rails-test-api/config/boot.rb:4:in `<top (required)>' from bin/rails:3:in `require_relative' from bin/rails:3:in `<main>'
环境信息
- 系统:Macbook Pro M1 Monterey 12.6(终端通过Rosetta启动)
- Ruby版本:
ruby 3.1.2p20 (2022-04-12 revision 4491bb740a) [x86_64-darwin21] - Rails全局版本:
Rails 7.0.4 - Bundler版本:
2.3.23 (2022-10-05 commit 250d9d485d) - Gem版本:
3.3.7
已尝试的无效操作
- 在Gemfile中添加
gem "bootsnap", require: false并执行bundle install,错误依旧 - 移除Gemfile中的bootsnap并注释
config/boot.rb里的require "bootsnap/setup",执行rails --version出现新错误:
❯ rails --version bin/rails:4:in `require': cannot load such file -- rails/commands (LoadError) from bin/rails:4:in `<main>'
- 在Gemfile添加
gem 'bootsnap'并执行bundle install,提示安装完成但项目内找不到该gem;手动执行gem install bootsnap成功,但bundle info bootsnap提示未找到
解决建议
1. 用Bundler加载项目依赖
这是最常见的问题——直接敲rails调用的是全局gem,而非项目本地依赖。项目内必须通过Bundler执行命令:
bundle exec rails -v
2. 彻底重装项目依赖
删除旧的依赖缓存和锁文件,重新安装:
rm Gemfile.lock rm -rf vendor/bundle bundle install
这样能避免之前安装的版本冲突或缓存问题。
3. 修复项目的binstubs文件
项目的bin/rails等脚本可能损坏,重新生成:
bundle binstubs rails --force
生成后再用bundle exec rails -v测试。
4. 恢复Bootsnap的默认配置
Bootsnap是Rails默认的优化组件,不要随意修改。先把Gemfile恢复成默认:
gem "bootsnap", require: false
执行bundle install后,不要注释config/boot.rb里的require "bootsnap/setup"——只要通过bundle exec执行命令,Rails会自动处理加载逻辑。
5. 检查Bundler的Ruby版本匹配
确认Bundler使用的Ruby版本和当前终端一致:
bundle platform
如果版本不匹配,重新指定Bundler的本地路径:
bundle config set --local path 'vendor/bundle' bundle install
内容的提问来源于stack exchange,提问作者Sonic Master
相关产品推荐
相关产品推荐

