macOS下Rails 3项目连接MySQL报错:undefined method `sub' for nil:NilClass
Hey there, I’ve run into this exact error before when setting up older Rails projects with MySQL—let’s walk through the most common fixes that should get you up and running:
Possible Causes & Solutions
Check for conflicting
DATABASE_URLenvironment variable
Rails prioritizes theDATABASE_URLenv var over yourdatabase.ymlconfig. If this variable is set to an invalid value or isnil, it’ll throw thatsuberror.- Run this in your terminal to check:
echo $DATABASE_URL - If you get any output (or even an empty line that indicates it’s set but empty), unset it with:
unset DATABASE_URL - Restart your Rails server after doing this.
- Run this in your terminal to check:
Pin the
mysql2gem to a Rails 3.2-compatible version
Newer versions of themysql2gem (0.4.x and above) aren’t compatible with Rails 3.2. You need to use a 0.3.x release.- Update your
Gemfileto include:gem 'mysql2', '~> 0.3.21' - Run
bundle installto install the correct version.
- Update your
Replace
localhostwith127.0.0.1in your database config
Sometimes macOS’s localhost resolution can cause issues with MySQL connections. Switching to the direct IP address often fixes this:
Update yourconfig/database.ymldefault section:default: &default adapter: mysql2 pool: 5 encoding: utf8 min_messages: warning timeout: 5000 username: root password: database: heart_development host: 127.0.0.1Verify MySQL is running
If MySQL isn’t active, Rails can’t connect at all.- If you installed MySQL via Homebrew, check its status with:
brew services list - If it’s not running, start it with:
brew services start mysql - Alternatively, check the MySQL icon in System Preferences to start the service.
- If you installed MySQL via Homebrew, check its status with:
Confirm your MySQL root user permissions
Make sure the root user can connect without a password from127.0.0.1/localhost:- Try logging into MySQL directly with:
mysql -u root - If this fails, you’ll need to reset your MySQL root password (follow the official MySQL docs for your version to do this).
- Try logging into MySQL directly with:
内容的提问来源于stack exchange,提问作者Nikita Kirilov

