Ruby on Rails 的 MySQL 亂碼問題
by ihower- Published:June 21st, 2006
- Comments:1 Comment
- Category:Database, Programming, Rails
剛開始認真玩 RoR,第一天就碰到 MySQL 中文字變亂碼的問題。雖然我已經改MySQL預設為 utf8,但還是一樣。根據以往 PHP 的經驗,應該是送 set names utf8 就可以解決了,那在 RoR 要怎麼弄,問 Google 的結果是找到這幾篇
- 如何在Ruby On Rails中使用Unicode
- Getting Unicode, MySql, and Rails to Cooperate
- How To Use Unicode Strings
在 /app/controllers/application.rb 的 ApplicationController 中加入以下設定
class ApplicationController < ActionController::Base
before_filter :configure_charsetsdef configure_charsets
@response.headers["Content-Type"] = “text/html; charset=utf-8″
# Set connection charset. MySQL 4.0 doesn’t support this so it
# will throw an error, MySQL 4.1 needs this
suppress(ActiveRecord::StatementInvalid) do
ActiveRecord::Base.connection.execute ‘SET NAMES UTF8′
end
end
end
另外當然資料庫跟資料表的 character要用 utf8 。




