Wednesday, September 14, 2011

Ruby 1.9.2, Rails 3.0 and MySQL2 Gem

Getting these two things to work together was not trivial. Here's a handy guide to save you some time. Using mysql2 gem is kind of mandatory if you plan on using UTF-8 extensively without running into "incompatible character encodings: ASCII-8BIT and UTF-8" -issue all the time.

Here is what you have to do.

  1. pre-reqs: Ruby 1.9.2 and Rails 3.0
  2. Remove libmysql.dll from c:\path-to-ruby\bin which can be there to fix this problem
  3. Remove mysql gem: gem remove mysql2
  4. Install Ruby Devkit from http://rubyinstaller.org/downloads/
  5. Install MySQL C Connector from http://www.mysql.com/downloads/connector/c/
  6. Copy over file c:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\lib\opt\libmysql.dll to c:\path-to-ruby\bin
  7. Install MySQL2 gem with gem install -v "0.2.11" mysql2 -- '--with-mysql-lib="C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\lib\opt" --with-mysql-include="C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include"'
  8. Change adapter from "mysql" to "mysql2" in your database.yml
  9. Change the line: gem 'mysql' to gem 'mysql2', "0.2.11" in your Gemfile
  10. Run bundle install

Make sure to follow Devkit's instructions when installing it. It should say "expanding PATH temporarily to include Devkit" when you are installing gems with C bindings like mysql. Also make sure you are using 32-bit versions of MySQL C Connector.

I'm not sure but the MySQL Server should ship with includes and libraries too. If you want to use them instead of the Connector, just point --with-mysql-include and --with-mysql-lib to correct directories, and make sure to copy MySQL Server's version of libmysql.dll to Ruby's binary folder.

You don't need -v "0.2.11" in the gem command line if you are using Rails 3.1 instead of 3.0.x.