why PG::UniqueViolation: ERROR: duplicate key value violates unique constraint?

前端 未结 3 461
一向
一向 2021-02-02 11:38

I have a model Post and each time a post is created I want a new instance of Moderation to be created at the same time.

So in post.rb I use the

相关标签:
3条回答
  • 2021-02-02 12:16

    To fix the issue, we have to tell ActiveRecord to look at the sequence of the table:

    ActiveRecord::Base.connection.reset_pk_sequence!('table_name')
    

    Now ActiveRecord should have the correct sequence value, and should be able to assign new id's properly.

    To resolve error

    PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "moderations_reportable" DETAIL: Key (reportable_type, reportable_id)=(Post, 25) already exists. : INSERT INTO "moderations" ("blog_id", "reportable_type", "reportable_id", "created_at", "updated_at", "blog_type") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"

    As error occurred on 'moderations' table.

    Run the following from rails console fix

    ActiveRecord::Base.connection.reset_pk_sequence!('moderations')
    

    Thank you

    0 讨论(0)
  • 2021-02-02 12:33

    Fix pkey sequences for all database:

    ActiveRecord::Base.connection.tables.each do |table_name| 
      ActiveRecord::Base.connection.reset_pk_sequence!(table_name)
    end
    
    0 讨论(0)
  • 2021-02-02 12:34

    Looks like you've added a unique index to your database:

    t.index ["reportable_type", "reportable_id"], name: "moderations_reportable", unique: true
    

    With a unique index you will only be able to have one record with the same reportable_type and reportable_id. It's likely that you're trying to create a moderation for a reportable that already has a moderation.

    0 讨论(0)
提交回复
热议问题