ruby-on-rails – 令人费解的“重复键”错误(PostgreSQL)

首先,让我说我理解关系理论,我和 MySQL中的任何人一样称职,但我是一个完整的Postgresql菜鸟.

当我尝试将新记录插入到我的服务表中时 – 仅在生产中 – 我得到了这个:

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'

我不明白为什么.它不应该为我自动增加PK吗?

这是表定义:

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服务;应该将序列重置为表中的当前最大值.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...