Ruby on Rails执行rails db:schema:dump时mysql2加载错误求助
LoadError: cannot load such file -- mysql2/2.4/mysql2 on Windows with Ruby 2.4 & Rails 5.0.7 Hey Danny, this is a super common hiccup when working with the mysql2 gem on Windows—let's walk through how to fix it step by step.
What's causing this error?
The error means the precompiled mysql2 gem binary you installed (version 0.4.10-x64-mingw32) doesn't have the correct native bindings for your Ruby 2.4 environment. The gem is looking for a file at mysql2/2.4/mysql2 that either doesn't exist or isn't compatible with your setup.
Step-by-Step Fixes
1. Uninstall the problematic mysql2 gem first
Open your command prompt and run:
gem uninstall mysql2
When prompted, select the 0.4.10-x64-mingw32 version to remove it.
2. Reinstall mysql2 with native bindings (recommended)
This ensures the gem is compiled specifically for your Ruby and MySQL setup. First, make sure you have MySQL Server installed (version 5.7 or 8.0 works best with Ruby 2.4).
If your MySQL is installed at the default path (C:\Program Files\MySQL\MySQL Server 8.0), run this command:
gem install mysql2 --platform=ruby -- '--with-mysql-dir="C:\Program Files\MySQL\MySQL Server 8.0" --with-mysql-lib="C:\Program Files\MySQL\MySQL Server 8.0\lib" --with-mysql-include="C:\Program Files\MySQL\MySQL Server 8.0\include"'
If you have MySQL installed elsewhere, replace the paths with your actual installation directory.
3. Fallback: Install a mysql2 version compatible with Ruby 2.4
If compiling native bindings gives you trouble, try installing version 0.5.3—it's known to work well with Ruby 2.4 on Windows:
gem install mysql2 -v 0.5.3 --platform=ruby
4. Update your Rails project's dependencies
Navigate back to your project directory and run:
bundle install
This ensures your Rails app uses the newly installed mysql2 gem instead of the old problematic one.
5. Verify the fix
Try running your original command again:
rails db:schema:dump
It should now connect to your database without the load error.
Quick Notes
- Always double-check that your
config/database.ymlhas the correctadapter: mysql2line, along with valid database name, username, and password. - Windows users often run into native gem issues—using the
--platform=rubyflag forces the gem to compile locally instead of relying on precompiled binaries that might not match your environment.
内容的提问来源于stack exchange,提问作者Danny Steiger

