今天早上我使用db:seed:dump恢复了数据库。现在,在尝试运行简单的rake文件后,我收到了以下错误。
ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "reports_pkey"
DETAIL: Key (id)=(1) already exists.
: INSERT INTO "reports" ("worker_id", "report_month", "status", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"
/path/to/app/dir/lib/tasks/produce.rake:22:in `block (3 levels) in <top (required)>'
/path/to/app/dir/lib/tasks/produce.rake:17:in `each'
/path/to/app/dir/lib/tasks/produce.rake:17:in `block (2 levels) in <top (required)>'
Caused by:
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "reports_pkey"
DETAIL: Key (id)=(1) already exists.
/path/to/app/dir/lib/tasks/produce.rake:22:in `block (3 levels) in <top (required)>'
/path/to/app/dir/lib/tasks/produce.rake:17:in `each'
/path/to/app/dir/lib/tasks/produce.rake:17:in `block (2 levels) in <top (required)>'
Tasks: TOP => produce:report_month
(See full trace by running task with --trace)
我之前已经运行过几次rake任务而没有错误,唯一的区别是我最近部署了一个备份。
读取错误似乎Rails正试图将ID间隔重新设置为1,这已经被占用。
seed:dump gem创建一个seeds.rb文件,其结构如下:
Note.create!([
{id: 1, notable_id: 51, notable_type: "Worker", body: "Some sort of text here", created_at: "2017-10-27 00:27:21", updated_at: "2017-10-27 00:27:21"},
{id: 2, notable_id: 68, notable_type: "Worker", body: "another note", created_at: "2017-11-11 18:43:13", updated_at: "2017-11-11 18:43:13"}
])
之前有没有遇到过这个?任何想法如何解决?
答案 0 :(得分:0)
我想Notes.id是一个序列号。种子手动设置id(id:1,id:2等),因此序列不被使用也没有递增。现在,您应该检查notes表中的最大id,并将序列设置为下一个值。
//tr[contains(., 'Label') and not(.//tr[contains(., 'Label')])]
答案 1 :(得分:0)
答案:不要使用db:seed:dump gem进行数据库备份。至少不是我使用它的方式。
我最终从通过pg_dump命令创建的早期备份中恢复。
感谢所有评论者