rails can't redefine the primary key column 'id'. To define a custom primary key主键找不到错误,错误信息如下:
you can't redefine the primary key column 'id'. To define a custom primary key, pass { id: false } to create_table.
为什么会出现这个错误呢?我们来还原一下这个问题。生成表我的shell语句如下:
rails g scaffold user id:integer name:string password:string
上面的语句说白了就是对应users表,其中id、name、password为数据库的列。创建表的sql语句如下:
create table users ( id int primary key auto_increment, name varchar(30), password varchar(30) );
我们执行生成模块的语句如下:
rails generate controller home index
产生的usersys/db/migrate 20170813075759_create_users.rb
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.integer :id t.varchar(30) :name t.varchar(30) :password t.timestamps end end end
上面的rb语句在rails3以下版本没有问题,但是我用的是rails5版本,所以报错,因此我要修改上面的sql逻辑,修改如下:
class CreateUsers < ActiveRecord::Migration[5.1] def change create_table :users, :id => false do |t| t.integer :id t.string :name t.string :password t.timestamps end end end
再次执行 rake db:migrate不报错了。
ok,本文先讲解到这里。
转载请注明:分享牛 » rails can't redefine the primary key column 'id'