gpt4 book ai didi

ruby-on-rails - 令人费解的 "duplicate key"错误 (PostgreSQL)

转载 作者:行者123 更新时间:2023-11-29 11:30:32 25 4
gpt4 key购买 nike

首先,让我说我了解关系理论并且我和 MySQL 中的任何人一样有能力,但我是一个完全的 PostgreSQL 菜鸟。

当我尝试向我的 service 表中插入一条新记录时 - 仅在生产中 - 我得到了这个:

ActiveRecord::RecordNotUnique (PGError: ERROR:  duplicate key value violates unique constraint "service_pkey"
: INSERT INTO "service" ("created_at", "name", "salon_id", "updated_at") VALUES ('2011-02-28 02:34:20.054269', 'Manicure', 1, '2011-02-28 02:34:20.054269') RETURNING "id"):
app/controllers/services_controller.rb:46
app/controllers/services_controller.rb:45:in `create'

我不明白为什么。它不应该为我自动增加 P​​K 吗?

这是表定义:

snip=> \d service
Table "public.service"
Column | Type | Modifiers
------------+-----------------------------+------------------------------------------------------
id | integer | not null default nextval('service_id_seq'::regclass)
name | character varying(255) |
salon_id | integer |
created_at | timestamp without time zone |
updated_at | timestamp without time zone |
Indexes:
"service_pkey" PRIMARY KEY, btree (id)

下面是开发中同一个表的定义,它工作正常:

snip_development=> \d service
Table "public.service"
Column | Type | Modifiers
------------+-----------------------------+------------------------------------------------------
id | integer | not null default nextval('service_id_seq'::regclass)
name | character varying(255) |
salon_id | integer |
created_at | timestamp without time zone |
updated_at | timestamp without time zone |
Indexes:
"service_pkey" PRIMARY KEY, btree (id)

同样的事情!那它可能是什么?

最佳答案

您可能已将数据加载到表中,但忽略了将 service_id_seq 的当前值设置为必要的值。您只需 SELECT * FROM service_id_seq 即可检查当前值,并使用 setval 函数对其进行重置。

例如,SELECT setval('service_id_seq'::regclass, MAX(id)) FROM service; 应该将序列重置为表中的当前最大值。

关于ruby-on-rails - 令人费解的 "duplicate key"错误 (PostgreSQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5137742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com