5

我收到以下错误:

ActiveRecord::StatementInvalid: PG::Error: ERROR: invalid byte sequence for encoding "UTF8": 0xf66e6bf6 : INSERT INTO "response_sets" ("city") VALUES ('Jönköping') RETURNING "id"

数据库是 Heroku 应用程序上的 PostgreSQL 9.0.6。

当有奇数字符时,不确定如何解决该错误。

4

3 回答 3

8

您的数据库未设置为与您尝试插入的字符串相同的编码方案。我想 Heroku 上的 Postgres 默认设置为使用 UTF-8,如果我不得不猜测,您的输入可能是拉丁语变体之一。您可以将数据库设置为接受您提供的编码方案,例如:

SET CLIENT_ENCODING 'ISO-8859-2'

或者您可以将输入转码为 UTF-8(这可能更好)

"my string".encode('UTF-8')
于 2012-10-04T14:01:40.533 回答
4

您的数据库可能未设置为与您插入的字符串相同的编码。Postgres 通常是 UTF-8。您必须在字符串上设置正确的编码。
这可能很简单

"string".encode('UTF-8')

或者,如果字符串标记不正确,您可能还必须先进行 force_encoding。IE。它存储为“Windows-1252”,但 Ruby 未将其标记为“Windows-1252”。

"string".force_encoding('Windows-1252').encode('UTF-8')

我们在使用 Sendgrid + Heroku Rails 时遇到了这个问题 http://blog.zenlike.me/2013/04/06/sendgrid-parse-incoming-email-encoding-errors-for-rails-apps-using-postgresql/

于 2013-04-06T08:54:59.673 回答
0

这似乎对我有用:

"Hern\xE1ndez".encode('UTF-8','ISO-8859-1')

第一个参数是您希望字符串所在的编码,第二个参数是您认为字符串所在的编码。

字符串#编码

文档中还有关于如何处理无效或未定义字符的选项。

这就是我最终使用的(为了安全起见):

"Hern\xE1ndez".encode('UTF-8','ISO-8859-1', :invalid => :replace, :undef => :replace, :replace => "?")

你也可以组成一个辅助方法:

def convert_to_utf_8(string)
  string.encode('UTF-8','ISO-8859-1', :invalid => :replace, :undef => :replace, :replace => "?")
end

我遇到的问题是从 Amazon Merchant Services API 加载数据。

于 2016-02-16T08:30:47.393 回答