在Rails中使用主键创建表和问题 [英] Creating tables and problems with primary key in Rails

查看:117
本文介绍了在Rails中使用主键创建表和问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用Mysql2作为数据库管理器在Rails中运行以下代码时:

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

rake db:migrate

我得到以下错误:

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

如果默认情况下表中的主键不是"null",为什么会出现此错误?

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

但是,迁移代码:

class CreateUsers < ActiveRecord::Migration
   def change
    create_table :users do |t|
     t.string "first_name"
     t.timestamps
    end
   end 
end

推荐答案

我之前也遇到过同样的问题,我根据这里解决了 https://github.com/rails/rails/pull/13247#issuecomment-32425844

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

使用Rails 2.3.5,MySQL 5.7.9版本和mysql gem需要具备 此位用作初始化程序 config/initializers/abstract_mysql_adapter.rb:

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

对于mysql2,它应该是config/initializers/abstract_mysql2_adapter.rb:

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

这篇关于在Rails中使用主键创建表和问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆