【问题标题】:Rails 3.1.0: incompatible character encodings: ASCII-8BIT and UTF-8Rails 3.1.0:不兼容的字符编码:ASCII-8BIT 和 UTF-8
【发布时间】:2011-12-14 01:15:32
【问题描述】:

我正在使用带有 PostgreSQL 的 Rails 3.1.0 和 Ruby 1.9.2。我想从大文件(~300mb)中获取数据并将其放入数据库。 这里我使用事务:

File.open("./public/data_to_parse/movies/movies.list").each do |line|
  if line.match(/\t/)
    title = line.scan(/^[^\t(]+/)[0]
    title = title.strip if title 
    year = line.scan(/[^\t]+$/)[0]
    year = year.strip if year
    movie = Movie.find_or_create(title, year)
    temp.push(movie) if movie
    if temp.size == 10000
      Movie.transaction do
        temp.each { |t| t.save }
      end    
       temp =[]
    end
  end
end

但我想通过原始 SQL 使用批量插入来提高性能:

temp.push"(\'#{title}\', \'#{year}\')" if movie
  if temp.size == 10000
   sql = "INSERT INTO movies (title, year) VALUES #{temp.join(", ")}" 
   Movie.connection.execute(sql)
   temp =[]
  end
end

但我有这个错误“不兼容的字符编码:ASCII-8BIT 和 UTF-8”。当我使用 activerecord 时,一切正常。 文件包含诸如德语变音符号之类的字符。我从这里Rails 3 - (incompatible character encodings: UTF-8 and ASCII-8BIT): 尝试了所有方法,但对我没有帮助。

你知道它是从哪里来的吗?

谢谢,

【问题讨论】:

    标签: ruby-on-rails utf-8 encode rails-postgresql


    【解决方案1】:

    解决了。问题出在文件编码中。它们在 ISO_8859-1 中,我通过 iconv 将其转换为 UTF-8。

    【讨论】:

    • 在这里为 iconv 加 1。 “iconv -f iso-8859-1 -t utf-8 YOURFILE > YOURFILE2 && MV YOURFILE2 YOURFILE”。另外,只是为 Google 员工添加 - 我在下载的 JavaScript 文件中遇到了这个问题。
    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 2012-07-12
    • 2011-10-17
    • 2016-04-27
    相关资源
    最近更新 更多