Rails 在控制器中输入中文字符会错误

413472212 · May 19, 2012 · Last by cantin replied at May 19, 2012 · 3223 hits

开发环境:ubuntu11.10,rails 3.1。 在控制器中出现中文的话会报错,错误信息如下:

SyntaxError (/home/shawnl/webproject/app/controllers/students_controller.rb:62: invalid multibyte char (US-ASCII)
/home/shawnl/webproject/app/controllers/students_controller.rb:62: invalid multibyte char (US-ASCII)
/home/shawnl/webproject/app/controllers/students_controller.rb:62: syntax error, unexpected $end, expecting keyword_then or ';' or '\n'
      if params[:student][:sex] == '男'
                                      ^):

在文件头加入#encoding: utf-8 就可以了。 想请教下大家在 application.rb 文件中已经设置编码格式为 utf-8 了,为什么还要在控制器文件中指定编码呢?

students_controller.rb 文件最上面加上 # coding: utf-8

#1 楼 @huacnlee 已经加了,可以避免这个错误。但我想问的是为什么 application.rb 文件已经设置了 utf-8 编码格式,但还要在控制器代码中指定编码,如果我有很多个文件里都要用到中文的话,那不是要每个文件都加一次#encoding: utf-8

个人理解,application 里面的 utf-8 是指程序的编码,比如前台传过来的参数的编码,而在.rb 文件上面是文件的编码,告诉 ruby 使用何种编码解析该文件。 求深入,求资料·····

#3 楼 @cantin 参见《松本行弘的程序世界》第 7 章 文字编码

#4 楼 @willmouse 谢谢,还有没有关于 rails3 的编码资料呢?

You need to Sign in before reply, if you don't have an account, please Sign up first.