"Rails 3, mysql and UTF-8"

So, have you started to work with rails 3? Did you realize that your UTF-8 databases doesn’t work nice with mysql? This is because the mysql gem works with ASCII-8BIT encoding, but ruby 1.9 and rails 3 works with UTF-8 encoding, so when you create a model into the database, everything works fine, but when you work with those models, it doesn’t works so nice and you don’t get what you stored.

What’s the solution? Well, there are actually three solutions, the most recommended, use mysql2, in order to do this, edit your Gemfile and include:

gem "mysql2"

and then, edit your databases.yml file, and change the adapter to mysql2

development:
  adapter: mysql2
  database: fun_development
  user: root
  password:
  encoding: utf8

Another solution, is just instead of using the “mysql” gem, use the “ruby-mysql” gem, but it’s pretty slow because it’s a 100% ruby gem.
view plaincopy to clipboardprint?

gem "ruby-mysql"

The last solution is a monkey patch, but its also slow to use it, so I really recommend using the mysql 2 gem view plaincopy to clipboardprint?

require 'mysql'
class Mysql::Result
  def encode(value, encoding = "utf-8")
    String === value ? value.force_encoding(encoding) : value
  end

  def each_utf8(&block)
    each_orig do |row|
      yield row.map {|col| encode(col) }
    end
  end
  alias each_orig each
  alias each each_utf8

  def each_hash_utf8(&block)
    each_hash_orig do |row|
      row.each {|k, v| row[k] = encode(v) }
      yield(row)
    end
  end
  alias each_hash_orig each_hash
  alias each_hash each_hash_utf8
end
Advertisements
"Rails 3, mysql and UTF-8"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s