最近瘋狂的愛上了ROR,開始用它做些小東西,可是總是出現亂碼問題,最後Google以下,找到了很多的解決中文亂碼問題的思路,總結與大家分享之。
開發環境:RedRails 使用編碼:UTF-8 資料庫:MySql
- 在radrails中,請在project的property對話方塊中,左邊選中info節點,右邊設定編碼方式為UTF-8
- 修改MySQL的設定檔C:\Program Files\MySQL\MySQL Server 5.0\my.ini,改其中的兩處default-character-set=utf8,改完後重啟MySQL(windows服務)。這一步也可採用instance wizard來做。
- 修改ApplicationController 如下:
class ApplicationController < ActionController::Base
before_filter :configure_charsets
def configure_charsets
# @headers["Content-Type"] = "text/html; charset=utf-8"
@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
- 請在rhtml中,或者適當的layout中,加上:
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
- 在config/database.yml修改如下:
development:
adapter: mysql
database: depot_development
encoding: utf8 *注意空格*
username: root
password:
host: localhost
儲存後,重啟ROR,啟動app,再次ruby script/generate scaffold Product Admin應該就行了。資料庫裡的表應該都是utf8_general_ci,rhtml也應該都是utf-8編碼。\app\views\layouts\admin.rhtml中加上<meta>標籤。
我用瞭解決了自己的中文亂碼問題,大家看看,希望可以和我一樣好運!!!