Ruby 1.9,MySQL字符编码问题
我们的Rails 3应用程序需要能够接受像ä和こ, 并将它们保存到我们的MySQL数据库中,该数据库的字符设置为“utf8” 我们的一个模型运行验证,该验证用于在保存之前去掉其名称中的所有非单词字符。在Ruby 1.8.7和Rails 2中,以下内容就足够了:Ruby 1.9,MySQL字符编码问题,mysql,ruby,encoding,ruby-1.9,Mysql,Ruby,Encoding,Ruby 1.9,我们的Rails 3应用程序需要能够接受像ä和こ, 并将它们保存到我们的MySQL数据库中,该数据库的字符设置为“utf8” 我们的一个模型运行验证,该验证用于在保存之前去掉其名称中的所有非单词字符。在Ruby 1.8.7和Rails 2中,以下内容就足够了: def strip_non_words(string) string.gsub!(/\W/,'') end 这就去掉了不好的字符,但保留了像“ä”这样的东西こ', 然而,在Ruby 1.9的新编码中,该语句不再有效——它正在删除这些
def strip_non_words(string)
string.gsub!(/\W/,'')
end
这就去掉了不好的字符,但保留了像“ä”这样的东西こ', 然而,在Ruby 1.9的新编码中,该语句不再有效——它正在删除这些字符以及我们不想要的其他字符。我正试图找到一种方法来做到这一点
将gsub更改为如下内容:
def strip_non_words(string)
string.gsub!(/[[:punct]]/,'')
end
def strip_non_words(string)
string_encoded = string.force_encoding(Encoding::ASCII_8BIT)
string_encoded.gsub!(/\p{Word}+/, '') # non-word characters
string_reencoded = string_encoded.force_encoding('ISO-8859-1')
string_reencoded #return
end
允许字符串很好地通过,但数据库会引发以下错误:
Mysql2::Error: Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation
通过Iconv运行字符串以尝试并转换它,如下所示:
def strip_non_words(string)
Iconv.conv('LATIN1', 'UTF8', string)
string.gsub!(/[[:punct]]/,'')
end
导致此错误的原因:
我在这里基本上已经穷途末路了。有人知道我需要什么吗?这是一个有趣的解决方案 我发现Ruby有一个我可以使用的正则表达式,但只能用于ASCII字符串。因此,我必须将字符串转换为ASCII,运行正则表达式,然后将其转换回提交给db。最终结果如下所示:
def strip_non_words(string)
string.gsub!(/[[:punct]]/,'')
end
def strip_non_words(string)
string_encoded = string.force_encoding(Encoding::ASCII_8BIT)
string_encoded.gsub!(/\p{Word}+/, '') # non-word characters
string_reencoded = string_encoded.force_encoding('ISO-8859-1')
string_reencoded #return
end
事实证明,由于Ruby处理更改字符编码的方式,您必须单独编码: