34
votes

I've got some troubles with the couple Rails 3.0.1, Ruby 1.9.2 and my website localization.

The problem is quite simple, i've got something like that in a view :

f.input :zip_code, :label => I18n.t('labels.zip_code')

and a es.yml file :

es:
  labels:
    zip_code: "Este código postal no es valido."

There are no troubles with the en.yml file (it's pure ASCII) but when the website is set with i18n.locale == 'es' I get this error :

incompatible character encodings: UTF-8 and ASCII-8BIT

I have been looking around for quite a while but didn't found a way to use my UTF-8 translation files.

Did some knows how to make it works ?

Thanks for your help.

5
This is sort of off topic, but Ryan Bates just posted a railscast (railscasts.com/episodes/256-i18n-backends) on i18n today. If anyone sees this comment the week of 3/6/2011, then in a way this comment is sort of relevant to you.aarona
James has a pretty nice tutorial on his blog, coverings almost all aspects of string encoding in Ruby 1.9. To understand what "external" and "internal" encoding mean, read it at: blog.grayproductions.net/articles/…Nicolas
Here's an awesome explanation of encoding on Rails: yehudakatz.com/2010/05/05/…B Seven

5 Answers

47
votes

Ok so problem solved after some hours of googling...

There was actually two bugs in my code. The first one was a file encoding error and the second was the problem with the MySQL Data base configuration.

First, to solve the error caused by MySQL I used this two articles :

http://www.dotkam.com/2008/09/14/configure-rails-and-mysql-to-support-utf-8/

http://www.rorra.com.ar/2010/07/30/rails-3-mysql-and-utf-8/

Second, to solve the file encoding problem I added these 2 lines in my config/environment.rb

Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8

Hopefully this will help someone :)

23
votes

I solved most of the problems by combining many solutions:

  • Make sure application.rb has this line: config.encoding = "utf-8".
  • Make sure you are using 'mysql2' gem
  • Putting # encoding: utf-8 at the top of any file containing utf-8 characters.
  • Add the following two lines above the <App Name>::Application.initialize! line in environment.rb:

    Encoding.default_external = Encoding::UTF_8
    Encoding.default_internal = Encoding::UTF_8
    

http://rorguide.blogspot.com/2011/06/incompatible-character-encodings-ascii.html

0
votes

Are you sure your es.yml file was saved as UTF-8?

If you're on Windows, use http://notepad-plus-plus.org/ to make sure.

0
votes

Using this unpack function helped me sort this out finally, try this if you get the can't convert error message:

myString.unpack('U*').pack('U*')
0
votes

Make sure you have config.encoding = "utf-8" in your config/application.rb. Also, your example translation file doesn't match the key you're searching for (com_name and first_name) but I suppose that could just be a typo.