2011-10-24 37 views
0

我使用Rails 3.1.0和Ruby 1.9.2與PostgreSQL。我想從大文件(〜300mb)中獲取數據並將其放入數據庫中。 這裏我使用的交易:Rails 3.1.0:不兼容的字符編碼:ASCII-8BIT和UTF-8

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 」。當我使用主動記錄時,一切正常。 文件包含德語變音符號等字符。我嘗試了所有從這裏Rails 3 - (incompatible character encodings: UTF-8 and ASCII-8BIT):,但它並沒有幫助我。

你知道它來自哪裏嗎?

謝謝,

回答

2

解決。問題在於文件編碼。他們在ISO_8859-1中,我通過iconv將它轉換爲UTF-8。

+0

+在此處顯示iconv。 「iconv -f iso-8859-1 -t utf-8 YOURFILE> YOURFILE2 && MV YOURFILE2 YOURFILE」。另外,只需爲Google員工添加 - 我在下載的JavaScript文件中遇到了這個問題。 –

相關問題