我错误地从表格的id字段中删除了自动增量选项.谁能告诉我如何通过迁移重新插入自动增量选项?
尝试:
change_column :my_table, :id, :primary_key
要么
my_table.change_column :id, :primary_key
某些Rails数据库适配器可能不允许您调用change_column
主键.如果是这种情况,那么您可以随时调用execute
直接使用SQL执行更改:
MySQL的:
execute('ALTER TABLE "my_table" CHANGE "id" "id" bigint DEFAULT NULL auto_increment PRIMARY KEY')
PostgreSQL(方法1):
max_id = execute(%%Q{SELECT id FROM "my_table" ORDER BY "id" DESC LIMIT 1}).to_a.first execute(%%Q{CREATE SEQUENCE "my_table_id_seq" START #{max_id+1}}) execute(%%Q{ALTER TABLE "my_table" ALTER COLUMN "id" TYPE bigint}) execute(%%Q{ALTER TABLE "my_table" ALTER COLUMN "id" SET DEFAULT nextval('my_table_id_seq'::regclass)}) execute(%%Q{ALTER TABLE "my_table" ADD PRIMARY KEY("id")})
PostgreSQL(方法2):
max_id = execute(%%Q{SELECT "id" FROM "my_table" ORDER BY "id" DESC LIMIT 1}).to_a.first execute(%%Q{ALTER TABLE "my_table" RENAME COLUMN "id" TO "id_orig"}) execute(%%Q{ALTER TABLE "my_table" ADD COLUMN "id" bigserial NOT NULL}) execute(%%Q{UPDATE "my_table" SET "id"="id_orig"}) execute(%%Q{ALTER SEQUENCE "my_table_id_seq" RESTART #{max_id+1}}) execute(%%Q{ALTER TABLE "my_table" DROP COLUMN "id_orig"})
如果你不希望使用bigint
/ bigserial
(64位),使用int(11)
/ integer
/ serial
来代替.
我没有检查其他版本,但是在Rails 5上,您可以设置以下auto_increment
选项:
change_column :table_name, :id, :int, null: false, unique: true, auto_increment: true
或者,如果您想要bigint:
change_column :table_name, :id, :bigint, null: false, unique: true, auto_increment: true