剛開始認真玩 RoR,第一天就碰到 MySQL 中文字變亂碼的問題。雖然我已經改MySQL預設為 utf8,但還是一樣。根據以往 PHP 的經驗,應該是送 set names utf8 就可以解決了,那在 RoR 要怎麼弄,問 Google 的結果是找到這幾篇

在 /app/controllers/application.rb 的 ApplicationController 中加入以下設定

class ApplicationController < ActionController::Base
before_filter :configure_charsets

def 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 。


Rss Commenti

1 Commento

  1. 其實不用這樣麻煩
    找個支援Unicode的編輯器
    database.yml的設定增加個
    encoding: utf8
    然後資料表用utf8_unicode_ci當collate
    我這樣做從來沒有再動過其他東西
    話說Ruby2.0有可能會修正Unicode的支援部份…

    #1 CFC

Lascia un Commento