在 Rails 3.x + Ruby 1.9 環境下,.html.erb 模板渲染 MySQL 讀取的中文數據時,常拋出 Encoding::CompatibilityError: incompatible character encodings: UTF-8 and ASCII-8BIT。本文針對根因定位、修復方案、最佳實踐進行系統說明。
ActionView::Template::Error (incompatible character encodings: UTF-8 and ASCII-8BIT):
app/views/posts/show.html.erb:12:in `_app_views_posts_show_html_erb___...'
模板期望 UTF-8 字符串,但 ActiveRecord 返回的字符串標記為 ASCII-8BIT(即 BINARY)。
encoding: utf8mb4,導致驅動默認用 latin1 或 binary 讀取。ASCII-8BIT 字節串。development:
adapter: mysql2
encoding: utf8mb4 # 關鍵:支援 emoji 與完整 Unicode
collation: utf8mb4_unicode_ci
database: myapp_dev
username: root
password: secret
host: localhost
pool: 5
gem 'mysql2', '~> 0.5' # Gemfile
bundle update mysql2
新版自動將結果集按連接編碼標記為 UTF-8,無需手動 .force_encoding。
# config/initializers/mysql_encoding.rb
ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.connection.execute("SET NAMES utf8mb4")
ActiveRecord::Base.connection.execute("SET CHARACTER SET utf8mb4")
end
在模板或控制器中強制轉碼:
<%= @post.content.force_encoding('UTF-8') %>
# 或控制器
@post.content = @post.content.force_encoding('UTF-8')
❌ 不推薦:治標不治本,易漏修,且掩蓋連接配置問題。
原文提到修改 mysql_adapter.rb 源碼,極不推薦:
SHOW VARIABLES LIKE 'character_set%'; 確認 character_set_server/client/connection/results = utf8mb4。SHOW CREATE TABLE t\G 確認 CHARSET=utf8mb4。SELECT HEX(col) FROM t LIMIT 1; 驗證中文編碼正確(如 E4BDA0E5A5BD = 你好)。incompatible character encodings 報錯。核心修復:database.yml 設定 encoding: utf8mb4 + 升級 mysql2 gem。徹底解決編碼不一致,避免模板層面的 force_encoding 打補丁。若遷移舊庫,務必先 ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4 修正存量數據編碼。