为何执行rails new会自动安装Rails 5.1.6而非指定的5.1.3?
Hey Ryan, I’ve run into this exact issue before—rbenv and Rails versioning can be tricky when global gems interfere with project-specific ones. Let’s break down what’s happening and fix it step by step:
Why You’re Seeing Rails 5.1.6 Instead of 5.1.3
- When you run
rails new demowithout specifying a version, it uses the latest globally installed Rails gem on your system. If you previously installed Rails 5.1.6 (even accidentally), that’s the version it’ll default to. - When you use
rails _5.1.3_ new demo, sometimes the auto-generated binstubs (the scripts in thebin/folder) can still point to the wrong Rails version if there’s a conflict with your environment.
Step-by-Step Fixes
1. Verify Your Rails Gem Installations
First, check which Rails versions are installed in your current Ruby environment:
gem list rails
You should see rails (5.1.3, 5.1.6) listed. If 5.1.3 isn’t there, install it explicitly for your active Ruby version:
gem install rails -v 5.1.3
2. Ensure You’re Using the Correct Ruby Version
Make sure you’re in the Ruby version where you installed Rails 5.1.3. Check your local project Ruby version:
rbenv local
If it’s not the right version, set it:
rbenv local <your-ruby-version> # e.g., rbenv local 2.4.2
Then re-run gem install rails -v 5.1.3 to ensure it’s installed for this Ruby version.
3. Regenerate Binstubs to Fix bin/rails about
The most common culprit for the version mismatch in bin/rails about is outdated binstubs. Here’s how to fix it:
- Navigate to your demo project directory:
cd demo - Delete the existing
bin/folder:rm -rf bin - Regenerate the binstubs using the Rails version specified in your Gemfile:
bundle exec rails app:update:bin - Now check the version again:
bin/rails about
This should now show Rails 5.1.3.
4. Prevent Global Rails Interference (Optional)
If you want to avoid this issue in the future, you can uninstall the global Rails 5.1.6 gem (if you don’t need it):
gem uninstall rails -v 5.1.6
Alternatively, use bundle exec for all Rails commands in your project to ensure you’re always using the version specified in your Gemfile.
Final Check
After these steps, double-check your project’s Gemfile—it should have:
gem 'rails', '~> 5.1.3'
And your Gemfile.lock should list rails (5.1.3) instead of 5.1.6.
内容的提问来源于stack exchange,提问作者Ryan

