【问题标题】:Rails 3.1, Ruby 1.9.2-p180 and UTF-8 issuesRails 3.1、Ruby 1.9.2-p180 和 UTF-8 问题
【发布时间】:2011-07-21 09:37:04
【问题描述】:

我在处理 UTF-8 字符时遇到了一些问题。这是 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。这是错误:

$ 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)

【问题讨论】:

    标签: ruby-on-rails utf-8 ruby-on-rails-3.1


    【解决方案1】:

    seeds.rb 文件的顶部添加这一行 # encoding: utf-8 并且任何 ruby​​ 文件都使用特殊字符

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

    最后,您可以将"".force_encoding('UTF-8) 添加到造成问题的字符串中。

    更新:

    在 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

    Source

    【讨论】:

    • 很好,成功了。希望它也适用于我的 AJAX 东西,因为它也无法正确显示字符。谢谢!
    • 是的,看来我还没有摆脱麻烦。突然之间,我的观点只给了我错误。 >_
    • 不要忘记在你的 database.yml 中为你的数据库适配器添加 encoding: utf8
    • 好电话,原来我的观点问题与 Rails 3.1 有关。名为 .coffee 的视图将错误地编码 UTF-8 或其他内容。
    猜你喜欢
    • 2011-09-17
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多