Error 'incompatible character encodings: ASCII-8BIT and UTF-8' due to 8-bit encoding of cookies (Rails 3 and Ruby 1.9)

Adolfo Builes picture Adolfo Builes · Mar 22, 2011 · Viewed 11.8k times · Source

I moved a web app that was using 1.8.7 to 1.9.2 and now I keep getting

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

I have the database encoding to UTF-8 and I have also 'config.encoding = "utf-8"'.

I saw some ideas as possible workarounds and I added

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

But it didn't work either.

One specific chunk of code where I am getting this error is

%ul.address
- @user.address.split(',').each do |line|
  %li= line.titleize

I'm using HAML, I checked line.titleize, and the encoding is UTF-8. Seems that the template is being rendered with ASCII-8BIT and it gets screwed each time that I try to render characteres like 'ñ'

I'm working with Rails 3.0.5.

I have read the post by James Edward Gray, but I still can figure it out what is going on ;(.

I'd really appreciate any kind of help :D.

I also tried:

"string".force_encoding("UTF-8")

And

# encoding: utf-8

Without any luck.

Fixed


See comments.

Answer

tardate picture tardate · Jul 12, 2011

I just ran into something similar ... and found the fix hidden in the comments to this question, but think it is worth highlighting explicitly:

cookies are ASCII-8BIT but rails 3 templates are utf-8 by default. This means using a raw cookie value in a view may raise Encoding::CompatibilityError (if the user has an incompatible in the cookie value)

The fix (as noted by Adolfo Builes) is to coerce your cookie values to UTF-8, as in:

cookies["location"].force_encoding('UTF-8')