2011-02-07 75 views
3

我正在使用Rails 3.0.3,並且已將mysql適配器從ruby-mysql更改爲mysql2,但現在出現以下錯誤:mysql2 gem,Rails 3.0.3和「不兼容的字符編碼」錯誤

incompatible character encodings: ASCII-8BIT and UTF-8 

我已經閱讀過關於此的所有內容,但我無法解決它。

application.rb中:

config.encoding = "utf-8" 

的database.yml:

development: 
    adapter: mysql2 
    encoding: utf8 
    database: rails3_development 
    username: root 
    password: 
    host: localhost 

寶石:

specs: 
    abstract (1.0.0) 
    actionmailer (3.0.3) 
    actionpack (3.0.3) 
    activemodel (3.0.3) 
    activerecord (3.0.3) 
    activeresource (3.0.3) 
    activesupport (3.0.3) 
    arel (2.0.7) 
    bcrypt-ruby (2.1.4) 
    builder (2.1.2) 
    erubis (2.6.6) 
    i18n (0.5.0) 
    jquery-rails (0.2.6) 
    mail (2.2.15) 
    mime-types (1.16) 
    **mysql2 (0.2.6) 
    orm_adapter (0.0.4) 
    paperclip (2.3.8) 
    polyglot (0.3.1) 
    rack (1.2.1) 
    rack-mount (0.6.13) 
    rack-test (0.5.7) 
    rails (3.0.3) 
    railties (3.0.3) 
    rake (0.8.7) 
    thor (0.14.6) 
    treetop (1.4.9) 
    tzinfo (0.3.24) 
    warden (1.0.3) 
    will_paginate (3.0.pre2) 
+0

對於其他搜索者:如果您使用mysql2和blob數據類型,它將始終返回二進制。只需將您的blob字段更改爲「文本」數據類型即可。它會保持編碼。 – 2012-11-06 13:57:47

回答

3

我有一個類似PROBL em:具有排序規則的varchar字段utf8_bin具有ASCII-8BIT編碼。

問題在於mysql2 gem,不是在Rails中,也不在mysql設置中,至少在我的情況下,因爲它不會發生在ruby-mysql gem中。

當您切換到ruby-mysql時,請測試問題是否消失。

下面的代碼,從IRB的紅寶石1.9.2運行,演示了此問題:

require 'mysql2' 
c = Mysql2::Client.new(host: "localhost", username: "root", database: 'd') 
c.query("select word from t where word = 'a'").to_a[0]["word"].encoding 
# => #<Encoding:ASCII-8BIT> 

這其中每一個可以想象的設置已被設置爲一個utf8_bin整理一個MySQL數據庫上。

在mysql2寶石,在上線253 result.c文件,有下面的代碼片段:

if (fields[i].flags & BINARY_FLAG) { 
    rb_enc_associate(val, binaryEncoding); 
} else ... 

我相信這就是二進制(ASCII-8BIT)編碼被設定,也許是因爲utf8_bin整理...我已經刪除它,並解決了問題,但我相信它可能會引入其他問題,例如blob。

+0

mysql2的作者在這裏迴應:https://github.com/brianmario/mysql2/issues/issue/124解決方案基本上是,不要使用utf8_bin,如果你必須的話,在字段上使用force_encoding。 – 2011-02-16 04:36:03

相關問題