【发布时间】:2010-10-11 13:04:55
【问题描述】:
我错误地从表的 id 字段中删除了自动增量选项。谁能告诉我如何通过迁移重新插入自动增量选项?
【问题讨论】:
标签: ruby-on-rails activerecord auto-increment rails-migrations
我错误地从表的 id 字段中删除了自动增量选项。谁能告诉我如何通过迁移重新插入自动增量选项?
【问题讨论】:
标签: ruby-on-rails activerecord auto-increment rails-migrations
这对我有用,创建了一个主列并为所有行提供了 ID。
add_column :tags_posts_rel, :id, :primary_key
【讨论】:
更改列
Rails5
change_column :table_name, :id, :int, null: false, unique: true, auto_increment: true, primary_key: true
Rails6
change_column :table_name, :id, :int, null: false, unique: true, auto_increment: true, primary_key: true
添加列 Rails5
add_column :table_name, :id, :int, null: false, unique: true, auto_increment: true, primary_key: true
Rails6
add_column :table_name, :id, :int, null: false, unique: true, auto_increment: true, primary_key: true
【讨论】:
对于那些来到这里(就像我一样)努力弄清楚如何制作使用bigint 而不是int 的自定义id 列的人,我没有意识到的是Rails 5.1 及以上版本,bigint 是 id 的默认类型
【讨论】:
我没有检查其他版本,但在 Rails 5 上,您可以设置 auto_increment 选项:
change_column :table_name, :id, :int, null: false, unique: true, auto_increment: true
或者如果你想要一个大整数:
change_column :table_name, :id, :bigint, null: false, unique: true, auto_increment: true
【讨论】:
primary_key: true
试试:
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(方法一):
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(方法二):
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。
【讨论】:
您的 Postgres 代码不起作用,不可能在 ALTER TABLE 语句中使用 serial 或 bigserial。 PostgreSQL 的正确 SQL 是
ALTER TABLE table ALTER COLUMN id TYPE int
ALTER TABLE table ALTER COLUMN id TYPE bigint
【讨论】: