由于cookie的8位编码而导致错误“不兼容的字符编码:ASCII-8BIT和UTF-8"(Rails 3和Ruby 1.9) [英] Error 'incompatible character encodings: ASCII-8BIT and UTF-8' due to 8-bit encoding of cookies (Rails 3 and Ruby 1.9)

查看:162
本文介绍了由于cookie的8位编码而导致错误“不兼容的字符编码:ASCII-8BIT和UTF-8"(Rails 3和Ruby 1.9)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使用1.8.7的Web应用程序移动到1.9.2,现在我不断获取

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

我的数据库编码为UTF-8,也有'config.encoding ="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

但是它也不起作用.

我收到此错误的特定代码段是

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

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

我正在使用HAML,我检查了line.titleize,其编码为UTF-8.似乎模板是使用ASCII-8BIT呈现的,并且每次我尝试呈现'ñ'之类的字符时都会搞砸

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 'ñ'

我正在使用Rails 3.0.5.

I'm working with Rails 3.0.5.

我已经阅读了詹姆斯·爱德华·格雷(James Edward Gray)的文章,但我仍然可以弄清楚发生了什么事((.

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

我非常感谢任何帮助:D.

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

我也尝试过:

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

还有

# encoding: utf-8

没有运气.

固定

查看评论.

推荐答案

我只是遇到了类似的问题...,并且发现此问题的注释中隐藏了此修复程序,但认为值得明确强调:

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

Cookie是ASCII-8BIT,但默认情况下,rails 3模板是utf-8.这意味着在视图中使用原始Cookie值可能会引发Encoding :: CompatibilityError(如果用户的Cookie值不兼容)

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)

解决方法(如Adolfo Builes所述)是将cookie值强制为UTF-8,如下所示:

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

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

这篇关于由于cookie的8位编码而导致错误“不兼容的字符编码:ASCII-8BIT和UTF-8"(Rails 3和Ruby 1.9)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆