Pro tip: Using mysql with Rails 3.0.0.beta2 and Ruby 1.9.2

I know NoSQL is upon us, but some of you might still be stuck with MySQL for the time being. Saying that, the mysql gem is not the best way to talk to your database using Ruby 1.9, at least if you are expecting UTF-8 characters to “just work”. The default mysql gem will simply ASCII-encode all the strings returned from the database, no matter what you set in database.yml. But fortunately, the solution is near! Just use the ruby-mysql gem instead. It is made by the same guy, Tomita Masahiro, but targets the 1.9 branch of Ruby.

For some reason I don’t understand, the current Rails 3 beta still uses the old mysql gem when you are generating a new application. So after running rails application awesome_shop -d mysql, you will have a gem 'mysql' entry in your Gemfile. Just change this entry to gem 'ruby-mysql', bundle install again and your are good to go!

See an example:

Using the old mysql gem:

In rails console:

rails console
Loading development environment (Rails 3.0.0.beta2)
ruby-1.9.2-head > p = Product.first
=> #<Product id: 1, title: "fd\xC3\xB6\xC3\xA4\xC3\xB6\xC3\xA4fdsf", description: "fasf \xC3\xB6a\xC3\xA4sf af\xC3\xB6\xC3\xA4fa ", created_at: "2010-04-03 08:34:52", updated_at: "2010-04-03 08:34:52">`

In the browser:

ActionView::TemplateError (incompatible character encodings: ASCII-8BIT and UTF-8)

Using the new, shiny ruby-mysql gem:

In rails console:

rails console
Loading development environment (Rails 3.0.0.beta2)
ruby-1.9.2-head > p = Product.first
=> #<Product id: 1, title: "fdöäöäfdsf", description: "fasf öaäsf aföäfa ", created_at: "2010-04-03 08:34:52", updated_at: "2010-04-03 08:34:52">`

In the browser:

No errors or whatsoever. UTF-8 awareness all the way down.

q.e.d :)

Show Comments