石锅拌饭

如何在Ruby On Rails中使用Unicode

by Robin Lu on Oct.06, 2005, about , , ,

这两天玩Ruby On Rails,测试中文输入的时候总是乱码。在Ruby On Rails的wiki里有一篇How To Use Unicode Strings,照着上面做,解决了部分问题,可在输入一些文字时仍然乱码,而且不是什么特殊的字符,比如“可”这个字,怎么都不对。google了半天也没有什么有价值的东西,最后祭出delicious,居然在rubyonrails+unicode的tag下找到了一篇Getting Unicode, MySql and Rails to Cooperate,终于解决了问题,目前看来还没有新问题出现。
总结一下,大概有这样几个要点:
在MySql这边,
1. 需要把Table的Type设置成为MyISAM而不是InnoDB。
2. 将Charecter设置成为utf8
就象这样:

create table samples (
id int not null auto_increment,
foo varchar(100) not null,
bar text not null,
primary key (id)
) Type=MyISAM CHARACTER SET utf8;

在Ruby On Rails这边,
1. 要设置enviroment.rb,加入

$KCODE = ‘u’
require ‘jcode’

2.在application.rb的ApplicationController中加入charset的设置,并显示告知MySql使用UTF8

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

然后就大功告成了。

:, , ,

3 Comments for this entry

1 Trackback or Pingback for this entry

Search

Archives

Browse by tags

agile apple blog book design ecto extension firefox git google hack ichm iphone keyword life mac madfox movie nonsense opensource plugin pm ruby rubyonrails sns software startup wordpress work 财帮子