简体   繁体   English

Rails to_json方法:Unicode字符问题

[英]Rails to_json method: problems with unicode characters

I'm having troubles with unicode characters in my Rails app. 我在Rails应用程序中遇到unicode字符的麻烦。 The problem is that when I store the object with some string containing scandinavian characters, those characters then are not rendered correctly when using to_json method. 问题是,当我用一些包含斯堪的纳维亚字符的字符串存储对象时,使用to_json方法时,这些字符将无法正确呈现。 Basically all those characters are rendered like this: 基本上所有这些字符都是这样绘制的:

\"description\":\"\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\"

Here is example: 这是示例:

 Item.create(:title => "Test title", :description => "With scandic characters öäöäö")
 => #<Item id: 198, title: "Test title", priority: nil, description: "With scandic characters öäöäö", bought_when: nil, warranty_until: nil, created_at: "2012-12-04 15:22:19", updated_at: "2012-12-04 15:22:19", user_id: nil, custom_id: nil, uuid: nil, position: 1, public: nil, secure_details: "", bookmark_id: nil, giveaway: nil, trash: false> 

At this point the created object looks ok. 此时,创建的对象看起来还可以。

 Item.last

returns 退货

 => #<Item id: 198, title: "Test title", priority: nil, description: "With scandic characters \xC3\xB6\xC3\xA4\xC3\xB6\xC3\xA4\xC3\xB6", bought_when: nil, warranty_until: nil, created_at: "2012-12-04 15:22:19", updated_at: "2012-12-04 15:22:19", user_id: nil, custom_id: nil, uuid: nil, position: 1, public: nil, secure_details: "", bookmark_id: nil, giveaway: nil, trash: false> 

This "With scandic characters \\xC3\\xB6\\xC3\\xA4\\xC3\\xB6\\xC3\\xA4\\xC3\\xB6" - does it still look ok? 这个“带有scandic字符\\ xC3 \\ xB6 \\ xC3 \\ xA4 \\ xC3 \\ xB6 \\ xC3 \\ xA4 \\ xC3 \\ xB6”-看起来还可以吗? Or do I miss some proper encoding already at the item creation stage? 还是在项目创建阶段就已经错过了一些适当的编码?

Anyway, now when call Item.last.to_json, I get this: 无论如何,现在调用Item.last.to_json时,我得到了:

"description\":\"With scandic characters \\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\"

And at this point the string is definitely broken. 至此,字符串肯定已断开。

I'm lacking some knowledge about the proper characters encoding in Rails, so any hints would be appreciated. 我缺少有关Rails中正确字符编码的知识,因此任何提示将不胜感激。 The item, however, looks fine when rendered in the browser - this happens only when doing a JSON response. 但是,该项目在浏览器中呈现时看起来不错-仅在执行JSON响应时才会发生。

Ok, the issue was that MySQL db was not in unicode. 好的,问题是MySQL数据库不是unicode。 This is fixed now by migrating to PosgreSQL, ensuring it is in unicode and using Taps gem to migrate the data. 现在可以通过迁移到PosgreSQL,确保它采用unicode并使用Taps gem来迁移数据来解决此问题。 All according to this Railscast: http://railscasts.com/episodes/342-migrating-to-postgresql 全部根据此Railscast进行: http: //railscasts.com/episodes/342-migrating-to-postgresql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM