Rails rails mysql 中文数据添加过程中出现的 Illegal mix of collations 错误解决方案

dailysunshine · 2015年09月25日 · 最后由 dailysunshine 回复于 2015年09月26日 · 3043 次阅读

development mode 用的是 sqlite3, production mode 用的是 mysql, 运行下面命令时出现 Illegal mix of collations 错误:

$ rake db:setup RAILS_ENV="production"

错误如下:

……
-- initialize_schema_migrations_table()
   -> 1.2291s
{"检测项目"=>"肥胖指数", "Category"=>"Obese", nil=>nil}
rake aborted!
ActiveRecord::StatementInvalid: Mysql2::Error: Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '=': SELECT  `traits`.* FROM `traits` WHERE `traits`.`cname` = '肥胖指数' LIMIT 1
/Users/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.3/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:305:in `query'
/Users/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.3/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:305:in `block in execute'
/Users/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.3/lib/active_record/connection_adapters/abstract_adapter.rb:473:in `block in log'
……

Google 了一下解决方法,错误仍然没有解决。如果大家也遇到过类似的,十分感谢能分享一下你的解决方案

PS, 下面是 databae.yml:

default: &default
  adapter: sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
 adapter: mysql2
 encoding: utf8    
 reconnect: false
 database: <%= ENV["DB"]%>
 pool: 5
 username: <%= ENV["DBUSER"]%>
 password: <%= ENV["DBPSWORD"]%>
 host: localhost
 socket: /Applications/MAMP/tmp/mysql/mysql.sock #TODO, change this to standard one in the server
 collation: utf8_general_ci  # google 搜索说需要加上这一句,不过也没有解决问题

用 utf8 来建表。

#1 楼 @msg7086 请问在哪一步操作呢

错误应该是由于我的 db/seeds.rb 中从文件读入的一些汉字到数据库中造成的

我自己的解决方案,

  1. 登陆 mysql 数据库
  2. 修改 rails app production 用的数据库编码方式 shell mysql> alter database rails_db character set utf8; 修改后问题就解决了 :)

不过网上还有一些其它方法: 如修改 /etc/my.cnf [mysqld]datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock default-character-set=utf8

需要 登录 后方可回复, 如果你还没有账号请 注册新账号