我升级到Rails 3之后,为什么所有字符串都变成了ASCII-8BIT编码?

7

我升级了RoR 3.0.1和Ruby 1.9.2。现在我视图中的所有字符串都是ASCII-8BIT编码?

我相信我的应用程序已经设置为使用UTF 8编码。

application.rb

config.encoding = "utf-8"

database.yml

development:
  adapter: mysql
  encoding: utf8

我在运行

OS X
RVM rvm 1.0.16 
Ruby ruby-1.9.2-p0
Rails 3.0.1

我认为编码应该是UTF-8而不是ASCII

business.desc.encoding
# ASCII-8BIT

自从1.9.x版本可以连接不同编码的字符串后,我们看到了很多像这样的错误。
<p class="description"><%= truncate(business.desc, :length => 17) %></p>

错误信息

incompatible character encodings: ASCII-8BIT and UTF-8

activesupport (3.0.1) lib/active_support/core_ext/string/output_safety.rb:74:in `concat'
activesupport (3.0.1) lib/active_support/core_ext/string/output_safety.rb:74:in `concat'
actionpack (3.0.1) lib/action_view/template/handlers/erb.rb:14:in `<<'
app/views/browse/businesses.html.erb:15:in `block in _app_views_browse_businesses_html_erb___1616718260917998189_2173630500__1134905695726531092'
app/views/browse/businesses.html.erb:3:in `each'
app/views/browse/businesses.html.erb:3:in `each_with_index'
app/views/browse/businesses.html.erb:3:in `_app_views_browse_businesses_html_erb___1616718260917998189_2173630500__1134905695726531092'

有其他人也遇到这个问题吗?使用ruby-1.9.2-p0版本是否正确?

谢谢!


你的数据库实际上是使用utf-8编码的,因为编码参数没有定义数据库编码。你也可以使用其他编码来创建数据库。 - shingara
3个回答

6

糟糕的问题。你需要将此放在每个文件的顶部。

# coding: UTF-8

使用Nerian描述的magic_encoding进行更新。

与下面的代码基本相同,但更好。

/UPDATE

我有一个rake任务,我不记得在哪里找到它(感谢那个人!),我稍微修改了一下,使其出现在每个文件的顶部。我听说过有人说上面的代码(你所做的)应该足够了,但对我来说并不起作用...

无论如何,这是rake任务,只需复制粘贴即可。


lib/tasks/utf8encode.rake

# coding: UTF-8

desc "Manage the encoding header of Ruby files"
task :utf8_encode_headers => :environment do
  files = Array.new
  ["*.rb", "*.rake"].each do |extension|
    files.concat(Dir[ File.join(Dir.getwd.split(/\\/), "**", extension) ])
  end

  files.each do |file|
    content = File.read(file)
    next if content[0..16] == "# coding: UTF-8\n\n" ||
            content[0..22] == "# -*- coding: utf-8 -*-"

   ["\n\n", "\n"].each do |file_end|
      content = content.gsub(/(# encoding: UTF-8#{file_end})|(# coding: UTF-8#{file_end})|(# -*- coding: UTF-8 -*-#{file_end})|(# -*- coding: utf-8 -*-#{file_end})/i, "")
    end

    new_file = File.open(file, "w")
    new_file.write("# coding: UTF-8\n\n"+content)
    new_file.close
  end
end

4
您需要将以下内容添加到每个.rb文件中:

<% # coding: UTF-8 %>

我会使用魔术编码宝石来实现这个功能。
$ cd app/ 
$ magic_encoding

默认编码为UTF-8,但你可以指定任何你想要的编码作为参数。

2

我正在从Ruby 1.8.6和Rails 2.3.5迁移到Ruby 1.9.2和Rails 3.0.3,并使用postregsql。为了使我的项目正常工作,我必须在任何需要翻译的视图模板的顶部添加以下内容:

<% # coding: UTF-8 %>

Ole提供的rake任务也应该很容易修改以实现此目的。虽然我发现他给出的解决方案没有任何效果。


哈哈...看起来我被20分钟打败了!在一个三个月前的问题上,这是什么几率。关于magic_encoding宝石的建议很好 - 我一定会自己尝试一下。 - Bob Wentz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接