You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS下Rails 3项目连接MySQL报错:undefined method `sub' for nil:NilClass

Fixing "undefined method `sub' for nil:NilClass" in Rails 3 + MySQL on macOS

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_URL environment variable
    Rails prioritizes the DATABASE_URL env var over your database.yml config. If this variable is set to an invalid value or is nil, it’ll throw that sub error.

    • 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.
  • Pin the mysql2 gem to a Rails 3.2-compatible version
    Newer versions of the mysql2 gem (0.4.x and above) aren’t compatible with Rails 3.2. You need to use a 0.3.x release.

    • Update your Gemfile to include:
      gem 'mysql2', '~> 0.3.21'
      
    • Run bundle install to install the correct version.
  • Replace localhost with 127.0.0.1 in your database config
    Sometimes macOS’s localhost resolution can cause issues with MySQL connections. Switching to the direct IP address often fixes this:
    Update your config/database.yml default section:

    default: &default
      adapter: mysql2
      pool: 5
      encoding: utf8
      min_messages: warning
      timeout: 5000
      username: root
      password:
      database: heart_development
      host: 127.0.0.1
    
  • Verify 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.
  • Confirm your MySQL root user permissions
    Make sure the root user can connect without a password from 127.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).

内容的提问来源于stack exchange,提问作者Nikita Kirilov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:07:59