简体   繁体   中英

Ruby On Rails and UTF-8

I have an Rails application with SayController , hello action and view template say/hello.html.erb . When I add some cyrillic character like "ю", I get an error:

ArgumentError in SayController#hello

invalid byte sequence in UTF-8

Headers:

{"Cache-Control"=>"no-cache",
 "X-Runtime"=>"11",
 "Content-Type"=>"text/html; charset=utf-8"}

If I try to write this letter with embedded Ruby,

<%= "ю" %>

I don't get any error, but it displays a question mark in black square ( ) instead of this letter.

I use Windows 7 x64, Ruby 1.9.1p378, Rails 2.3.5, WEBrick server.

A likely cause of this error is that the file which contains the cyrillic letters is not encoded in UTF8, but perhaps in some russian encoding like KOI8. This will cause the characters to be impossible to interpret in UTF8 (and rightly so!).

So double check that your file is properly encoded in UTF8.

Create a initializer file (eg encoding_fix.rb) under your_app/config/initializers with the following content:

Encoding.default_internal = Encoding::UTF_8 if RUBY_VERSION > "1.9"
Encoding.default_external = Encoding::UTF_8 if RUBY_VERSION > "1.9"

This sets the encoding to utf8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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