Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL changes UTF-8 to ASCII-8BIT

I've this scenario.

A movie title:

$ title = "La leyenda de Osaín"

With this encoding:

$ title.encoding.name
>> UTF-8

I then saves it to the database.

$ movie = Movie.create!(:title => title)

Then I try to get the movie.

$ Movie.find(movie.id).title.encoding.name
>> "ASCII-8BIT"

$ Movie.find(movie.id).title
>> "La leyenda de Osa\xC3\xADn"

All other movies works that does not contain special characters like í and û.

This is my database.yaml file:

development:
  adapter: mysql
  database: development
  username: linus
  password: my_password
  socket: /tmp/mysql.sock
  encoding: UTF8

I'm getting the right sort of data when using forced_encoding.

$ Movie.find(movie.id).title.force_encoding("UTF-8")
>> "La leyenda de Osaín"

I'm using Rails 3.0.5.rc1 with MySQL 14.14.

Anyone knows what the problem may be?

like image 915
Linus Oleander Avatar asked Feb 25 '11 21:02

Linus Oleander


1 Answers

I found a solution to my problem. Now I'm using the newer mysql2 gem.

I replaced gem "mysql" with gem "mysql2" inside the Gemfile.

Then I changed the database adapter inside the database.yaml file.

From:

development:
  adapter: mysql
  database: development
  username: linus
  password: my_password
  socket: /tmp/mysql.sock
  encoding: UTF8

To:

  development:
    adapter: mysql2
    database: development
    username: linus
    password: my_password
    socket: /tmp/mysql.sock
    encoding: UTF8

I think this was the deal breaker in my case:

Taken from Github MySQL2

[...]It also forces the use of UTF-8 [or binary] for the connection [and all strings in 1.9[...]

like image 151
Linus Oleander Avatar answered Oct 09 '22 17:10

Linus Oleander