如何清理字符串以存储在sqlite数据库中?

时间:2012-07-24 03:40:09

标签: ruby-on-rails sqlite sanitization

我正试图在sqlite数据库中存储来自mp3的标签,我收到以下错误:

 
SQL (0.3ms)  INSERT INTO "songs" ("album", "artist", "created_at", "length", "path", "store_id", "title", "track_number", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)  [["album", "\xFF\xFE2\x001\x00"], ["artist", "\xFF\xFEa\x00d\x00e\x00l\x00e\x00"], ["created_at", Tue, 24 Jul 2012 03:34:03 UTC +00:00], ["length", 15], ["path", "/audios/music/Adele - Discography (Complete) [2008 - 2011]/Adele - 21 [2011] + Bonus Tracks/01. Adele - Rolling in the Deep.mp3"], ["store_id", 3], ["title", "\xFF\xFEr\x00o\x00l\x00l\x00i\x00n\x00g\x00 \x00i\x00n\x00 \x00t\x00h\x00e\x00 \x00d\x00e\x00e\x00p\x00"], ["track_number", "01"], ["updated_at", Tue, 24 Jul 2012 03:34:03 UTC +00:00]]
Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8: INSERT INTO "songs" ("album", "artist", "created_at", "length", "path", "store_id", "title", "track_number", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
   (0.2ms)  rollback transaction
ActiveRecord::StatementInvalid: Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8: INSERT INTO "songs" ("album", "artist", "created_at", "length", "path", "store_id", "title", "track_number", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
 

我如何剥离或消毒输入?

1 个答案:

答案 0 :(得分:1)

ActiveRecord抱怨Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8,但很明显\xFF\xFE2\x001\x00不在ASCII-8BIT编码中。因此,您可以通过在调用ActiveRecord之前将id3标记转换为UTF-8来解决此问题。

"source string".encoding(dst_encoding, src_encoding).

文档:http://www.ruby-doc.org/core-1.9.3/String.html#method-i-encode