您的位置:首页 > 数据库 > MySQL

解决rails与mysql结合使用时的中文乱码问题

2010-08-27 00:37 1091 查看
Rails MySQL 中文乱码问题解决
2008-03-02 16:01
 

RoR+MySQL搭建的程序。
当输入英文的时候,程序不报错,当输入中文出现的错误提示:

Mysql::Error: #HY000Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '=': SELECT * FROM `users`   WHERE (`users`.`email` = '阿')  LIMIT 1

这是字符编码混合而产生的错误,解决办法是将表的编码修改成一致的。
语法:ALTER TABLE tbl_name CONVERT TO CHARACTER SET   utf8;  

也可以通过migrate指定:
class CreateUsers < ActiveRecord::Migration   

  def self.up   

     create_table :users, : options => 'CHARSET=utf8' do |t|   

       t.column :name, :string  

       t.column :password, :string  

       t.column :birthday, :datetime  

       t.column :email, :string  

       t.column :address, :text  

    end  

  end  

  

  def self.down   

     drop_table :users  

  end  

end  

其实解决中文问题很简单: 

1、确定MySQL数据库编码是utf8 
2、database.yml里面增加encoding: utf8 
3、确定rhtml文件编码是UTF-8

1、确定MySQL数据库编码是utf8

     跟上面同理

2、database.yml里面增加encoding: utf8

development:
adapter: mysql
encoding: utf8
database: song
username: root
password: 
host: localhost

3、确定rhtml文件编码是UTF-8

修改application.rb文件:
class ApplicationController < ActionController::Base

before_filter :set_charset   
before_filter :configure_charsets  

#中文乱码解决方案
def set_charset   
    headers["Content-Type"] = "text/html; charset=utf-8" 
end   

def configure_charsets   
    response.headers["Content-Type"] = "text/html; charset=utf-8" 
    suppress(ActiveRecord::StatementInvalid) do 
      ActiveRecord::Base.connection.execute 'SET NAMES UTF8' 
    end
   
end

end
在网页中,添加meta标签:
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

$(".MathJax").remove();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐