在 Rails 中正确处理 unicode 字符
默认情况下,Rails 允许应用程序的用户输入非 utf8 数据,例如: ¶®«¼
但是,当我们尝试从数据库中检索数据并将其呈现在模板中时,Rails 错误地认为:它是 UTF-8 格式并引发错误。
ArgumentError: invalid byte sequence in UTF-8
处理这个问题的最佳方法是什么?我看到一个修复建议在用户可以输入数据的每个地方清理数据。然而,这将涉及更改大量代码,并且会完全删除字符。理想情况下,我们希望将一些字符转换为其 UTF-8 等效字符。
我们的环境:
Ruby: 1.9.1
Rails 2.3.5
MySql Gem: 2.8.1
这对我们来说是一个严重而紧迫的问题,因此非常感谢您的回答!
By default Rails allows users of our application to input non-utf8 data, such as: ¶®«¼
However when we attempt to retrieve the data from our database and render it in a template Rails incorrectly assumes that it is in UTF-8 format and throws an error.
ArgumentError: invalid byte sequence in UTF-8
What is the best way to handle this? I have seen one fix that suggested sanitizing the data in every place the user can input it. However, that would involve changing a considerable amount of code and it would strip out the characters entirely. Ideally we would want some characters converted to their UTF-8 equivalents.
Our environment:
Ruby: 1.9.1
Rails 2.3.5
MySql Gem: 2.8.1
This is a serious and urgent problem for us so your answers are very appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 mysql2 gem(版本 0.1.6 或更高版本)而不是 mysql。
它仍然相当新,但在生产中对我来说运行良好,并且将从数据库中检索所有字符串作为 utf-8。
只需安装 gem 并更改您的database.yml 文件以包含“适配器:mysql2”
Try using the mysql2 gem (version 0.1.6 or greater) instead of mysql.
It's still fairly new, but has been working well for me in production and will retrieve all strings from your DB as utf-8.
Just install the gem and change your database.yml file to contain "adapter: mysql2"