不兼容的字符编码:Ruby 1.9 中的 ASCII-8BIT 和 UTF-8 [英] incompatible character encodings: ASCII-8BIT and UTF-8 in Ruby 1.9

查看:65
本文介绍了不兼容的字符编码:Ruby 1.9 中的 ASCII-8BIT 和 UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Ruby 1.9 & 出现以下错误导轨 2.3.4.当用户提交非 ASCII 标准字符时会发生这种情况.

I'm getting the following error with my Ruby 1.9 & Rails 2.3.4. This happens when user submits a non-ASCII standard character.

我阅读了很多在线资源,但似乎没有一个有效的解决方案.

I read a lot of online resources but none seems to have a solution that worked.

我尝试使用(如某些资源所建议的那样)

I tried using (as some resources suggested)

string.force_encoding('utf-8') 

但它没有帮助.

任何想法如何解决这个问题?有没有办法在保存到数据库之前消除这些字符?或者,有没有办法让它们显示出来?

Any ideas how to resolve this? Is there a way to eliminate such characters before saving to the DB? Or, is a there a way to make them show?

推荐答案

我对 Ruby(或 Rails)了解不多,但我想问题是由于缺乏对字符编码的控制造成的.

I don't know much about Ruby (or Rails), but I imagine the problem is caused by a lack of control over your character encodings.

首先,您应该决定要在数据库中存储哪种编码.然后,您需要确保在存储到数据库之前将所有文本转换为该编码.为此,您首先需要知道它以哪种编码开始.

First, you should decide which encoding you're storing in your database. Then, you need to make sure to convert all text to that encoding before storing in the database. In order to do that, you first need to know which encoding it is to begin with.

一个经常重复的建议是在您控制它后尽快将所有输入从它使用的任何编码解码为 un​​icode(如果您的语言支持它).然后您知道您在程序中处理的所有文本都是 unicode.另一方面,将文本编码为您想要的任何输出编码,作为输出之前的最后一步.

One often repeated piece of advice is to decode all input from whatever encoding it uses, to unicode (if your language supports it) as soon as possible after you get control of it. Then you know that all the text you handle in your program is unicode. On the other end, encode the text to whatever output-encoding you want as a last step before outputting it.

关键是要始终知道一段文本在代码中的任何给定位置使用的是哪种编码.

The key is to always know which encoding a piece of text is using at any given place in your code.

这篇关于不兼容的字符编码:Ruby 1.9 中的 ASCII-8BIT 和 UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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