Rails 3.1,Ruby 1.9.2-p180和UTF-8问题 [英] Rails 3.1, Ruby 1.9.2-p180 and UTF-8 issues

查看:62
本文介绍了Rails 3.1,Ruby 1.9.2-p180和UTF-8问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用UTF-8字符时遇到了麻烦.这是db/seeds.rb

I'm having some trouble with UTF-8 characters. Here's db/seeds.rb

User.create(username: 'eml', first_name: '****', last_name: '****äck', 
            email: 'somemail@example.com', password: 'asdasd')

我的终端(OSX 10.5.8)设置为使用UTF-8,Rails(根据application.rb)设置为使用utf-8.这是错误:

My terminal (OSX 10.5.8) is set to use UTF-8, Rails (according to application.rb) is set to use utf-8. Here's the error:

$ rake db:seed
rake aborted!
/Projects/***/db/seeds.rb:8: invalid multibyte char (US-ASCII)
/Projects/***/db/seeds.rb:8: invalid multibyte char (US-ASCII)
/Projects/***/db/seeds.rb:8: syntax error, unexpected $end, expecting ')'
...ame: '****', last_name: '****äck', 
...                               ^

Tasks: TOP => db:seed
(See full trace by running task with --trace)

推荐答案

seeds.rb文件顶部添加此行# encoding: utf-8,任何红宝石文件都使用spécials字符

Add this line # encoding: utf-8 on the top of seeds.rb file and any ruby file use spécials chars

我建议您将Encoding.default_external = "UTF-8"添加到config.ru文件和config/environment.rb中以进行模板编码

I recommed you to adding Encoding.default_external = "UTF-8" to config.ru file and in config/environment.rb for encoding templating

最后,您可以在出现问题的字符串中添加"".force_encoding('UTF-8).

And finally you can add "".force_encoding('UTF-8) to your string that pose problems.

更新:

在config.ru上添加整行:

Add full line on config.ru :

# Not override -E option or LANG and apply only for ruby > 1.9
if Object.const_defined?(:Encoding) && !ENV['LANG'] && !ENV['RUBYOPT'].include?('-E')
Encoding.default_internal = 'utf-8'
Encoding.default_external = 'utf-8'
end

# Not override -E option or LANG and apply only for ruby > 1.9
if Object.const_defined?(:Encoding) && !ENV['LANG'] && !ENV['RUBYOPT'].include?('-E')
Encoding.default_internal = 'utf-8'
Encoding.default_external = 'utf-8'
end

来源

这篇关于Rails 3.1,Ruby 1.9.2-p180和UTF-8问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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