我正在尝试通过 rake 任务将数据从一个数据库移动到另一个数据库。
但是,我在某些数据上遇到了一些果味编码问题:
rake aborted!
PGError: ERROR: invalid byte sequence for encoding "UTF8": 0x92
HINT: This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding".
如何解决此错误并获取数据?据我所知(对编码一无所知),源数据库是 latin1。
最佳答案
如果两个数据库都是 PG,那么您可以使用 pg_dump 选项更改编码来导出和导入整个数据库...这可能是最高效的方法
如果你通过 rake 任务执行此操作,你可以在你的 rake 任务中进行转码......这实际上意味着你将不得不触及每个属性并重新编码......
因为看起来你的新数据库是 utf8 而旧的是 latin1
您可以通过使用...检查 respond_to?(:encoding) 对每个字符串/文本/类似文本的值进行编码来确保数据仅在附加了一些编码信息时才被编码,即。 e.数值不会被转码
def transcode(data, toEnc = 'utf8')
if data.respond_to?(:encoding) && data.encoding.name != toEnc
return data.dup.force_encoding toEnc
end
data
end
现在你可以从旧数据库中读取一条记录,通过这个方法运行它,然后将它写入新数据库
u = OldDBUser.first
u.attribute_names.each { |x|
u[x.to_sym] = transcode u[x.to_sym]
}
#... whatever you do with the transcoded u
...好吧,我还没有测试过这些,但请测试一下,也许这就是您所需要的
关于ruby-on-rails - 使用 Rails 移动编码数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4398266/