Rails 3.1.0:不兼容的字符编码:ASCII-8BIT 和 UTF-8
我将 Rails 3.1.0 和 Ruby 1.9.2 与 PostgreSQL 一起使用。我想从大文件(~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 - (不兼容的字符编码: UTF-8 和 ASCII-8BIT):,但这对我没有帮助。
你知道它来自哪里吗?
谢谢,
I'm using Rails 3.1.0 and Ruby 1.9.2 with PostgreSQL. I want to get data from huge files (~300mb) and put it in database.
Here i use transaction:
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
But i want to improve perfomance using mass insert whith raw 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
But i have this error "incompatible character encodings: ASCII-8BIT and UTF-8". When i'm using activerecord it's all ok.
Files contains characters such as German umlauts. I tried all from here Rails 3 - (incompatible character encodings: UTF-8 and ASCII-8BIT):, but it doesn't help me.
Do you have any idea where it comes from ?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决了。问题出在文件编码上。它们位于 ISO_8859-1 中,我通过 iconv 将其转换为 UTF-8。
Solved. Problem was in files encoding. They were in ISO_8859-1 and i converted it to UTF-8 via iconv.