部署Rails应用至Heroku时遇pg版本冲突错误求助
Hey there, let's work through this frustrating pg gem version issue together—deploying your first Rails app should feel exciting, not like a late-night headache! Let's break down what's happening and fix it step by step:
What's Going Wrong Here
The error tells us two key things:
- Heroku is trying to use the
pggem specified in your production group (~>0.18), but your local environment has a newer version (1.0.0) activated that's causing a conflict. - Even after adjusting your Gemfile, the lock file or cached gems are still creating a mismatch between what your app expects and what's actually installed.
Step-by-Step Fixes
1. Lock Down the Exact PG Version in Your Gemfile
Instead of using the fuzzy ~>0.18 constraint, specify an exact patch version to eliminate ambiguity. Update your production group in Gemfile to:
group :production do gem 'pg', '0.18.4' # This is the latest stable patch in the 0.18 series end
2. Clean Up Local PG Gem Versions
Let's ensure your local environment only has the version we need:
- Run
gem uninstall pgin your terminal. When prompted, select all versions to uninstall existing pg gems. - Install the exact version we specified:
gem install pg -v 0.18.4
3. Regenerate Your Gemfile Lock (And Fix Cross-Platform Mismatches)
Heroku runs on Linux, while your local machine might be macOS/Windows—this can cause gem version mismatches in the lock file. Let's fix that:
- Delete the old lock file:
rm Gemfile.lock - Add Heroku's Linux platform to your bundle so it locks the correct gem version for deployment:
bundle lock --add-platform x86_64-linux - Run
bundle installto generate a fresh, cross-platform-compatible lock file.
4. Clear Heroku's Build Cache (Just in Case)
Sometimes Heroku caches old gems from previous deployments. Let's wipe that cache to start fresh:
- First install the Heroku builds plugin if you don't have it:
heroku plugins:install heroku-builds - Purge the cache:
heroku builds:cache:purge
5. Commit and Deploy
Now let's push the fixes to Heroku:
git add Gemfile Gemfile.lock git commit -m "Fix pg gem version conflict for Heroku deployment" git push heroku master
Quick Double-Check
Make sure your config/database.yml file's production section looks like this (no extra version constraints):
production: adapter: postgresql encoding: unicode pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> database: your_app_name_production username: your_app_name password: <%= ENV['YOUR_APP_NAME_DATABASE_PASSWORD'] %>
That should resolve the version mismatch and let your app connect to Heroku's PostgreSQL database properly. Good luck with your first Rails app—you've got this!
内容的提问来源于stack exchange,提问作者M. Outen

