Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

mysql - Creating tables and problems with primary key in Rails

When I try to run the following code in Rails using Mysql2 as database manager:

rake db:migrate

I obtain the following error:

 rake aborted!
 "Mysql2::Error: All parts of a PRIMARY KEY must be NOT NULL:"

Why do I get this error, if the primary key in a table by default is NOT "null"?

Migration code, however :

class CreateUsers < ActiveRecord::Migration
   def change
    create_table :users do |t|
     t.string "first_name"
     t.timestamps
    end
   end 
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had a same problem before, and I solved according to here https://github.com/rails/rails/pull/13247#issuecomment-32425844

With Rails 2.3.5, MySQL version 5.7.9 and mysql gem you need to have this bit as an initializer in config/initializers/abstract_mysql_adapter.rb:

class ActiveRecord::ConnectionAdapters::MysqlAdapter
  NATIVE_DATABASE_TYPES[:primary_key] = "int(11) auto_increment PRIMARY KEY"
end

For mysql2, it should be config/initializers/abstract_mysql2_adapter.rb:

class ActiveRecord::ConnectionAdapters::Mysql2Adapter
  NATIVE_DATABASE_TYPES[:primary_key] = "int(11) auto_increment PRIMARY KEY"
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...