Rails 3,heroku - PGError:错误:编码"UTF8"的无效字节序列:

AnA*_*ice 5 ruby-on-rails ruby-on-rails-3

我只是在heroku(postgres)上通过Rails 3随机得到这个奇怪的错误

PGError: ERROR: invalid byte sequence for encoding "UTF8": 0x85 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". : INSERT INTO "comments" ("content") VALUES ('BTW?I re-listened to the video' ......
Run Code Online (Sandbox Code Playgroud)

很好的暗示并没有为我点击任何东西.我可以在某处设置编码吗?我应该惹这个吗?有人看过这个和/或对如何处理这类问题有任何想法?

谢谢

von*_*rad 6

从我可以收集到的,这是一个问题,你试图插入PostgrSQL服务器的字符串不是用UTF-8编码的.这有点奇怪,因为您的Rails应用程序应配置为默认使用UTF-8.

有几种方法可以尝试修复此问题(按照我推荐的顺序):

  • 首先,确保config.encoding被设置为"utf-8"config/application.rb.

  • 如果您使用的是Ruby 1.9,则可以尝试在插入之前强制执行字符编码toutf8.

  • 你可以弄清楚你的字符串是用什么编码的,并SET CLIENT_ENCODING TO 'ISO-8859-1';在插入字符串之前手动设置PostgeSQL连接上的(或编码).不要忘记RESET CLIENT_ENCODING;在声明后重置编码.

  • 如果你正在使用Ruby 1.8(更有可能),你可以使用iconv库将字符串转换为UTF-8.见文档这里.

  • 更hackish的解决方案是重写你的getter和setter的模型(即contentcontent=)编码和解码使用Base64您的字符串.它看起来像这样:

 

require 'base64'

class Comment
  def content
    Base64::decode64(self[:content])
  end

  def content=(value)
    self[:content] = Base64::encode64(value)
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 我相信`iconv`应该适用于1.8和1.9.至于代码,这样的东西应该工作:`content = :: Iconv.conv('UTF-8 // IGNORE','UTF-8',内容+'')[0 ..- 2]`.基本上,这会强制编码为UTF-8,无论它最初是什么.我从这里得到了代码:http://stackoverflow.com/questions/4583924/string-force-encoding-in-ruby-1-8-7-or-rails-2-x/4585362#4585362 (3认同)