我有一个模型Post,每次创建帖子时,我都希望同时创建Moderation的一个新实例.

所以在邮报上.rb我使用回调after_save :create_moderation

 ...
 include Reportable
 after_save :create_moderation

 private
 def create_moderation
    self.create_moderation!(blog: Blog.first)
 end

但是当一个提议被创建时,我会遇到这样的错误:

PG::UniqueViolation:错误:重复键值违反了唯一约束"可报告"详细信息:键(可报告类型,可报告id)=(Post,25)已存在:将($1,$2,$3,$4,$5,$6)返回"id"值插入"审核"("博客id","可报告类型","可报告类型","创建日期","更新日期","博客类型")

以可报告的形式.rb我有:

  has_one :moderation, as: :reportable, foreign_key: "reportable_id", foreign_type: "reportable_type", class_name: "Moderation"

然后是其他几个可报告对象的方法.

注意,当我在控制台中运行create方法时,这个问题不会发生.

EDIT

  create_table "moderations", id: :serial, force: :cascade do |t|
    t.string "reportable_type", null: false
    t.string "reportable_id", null: false
    t.integer "blog_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "blog_type", null: false
    t.string "upstream_moderation", default: "unmoderate"
    t.index ["blog_id", "blog_type"], name: "moderations_blog"
    t.index ["reportable_type", "reportable_id"], name: "moderations_reportable", unique: true
  end



create_table "posts", id: :serial, force: :cascade do |t|
    t.text "title", null: false
    t.text "body", null: false
    t.integer "feature_id", null: false
    t.integer "author_id"
    t.integer "scope_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "post_votes_count", default: 0, null: false
    t.index ["body"], name: "post_body_search"
    t.index ["created_at"], name: "index_posts_on_created_at"
    t.index ["author_id"], name: "index_posts_on_author_id"
    t.index ["feature_id"], name: "index_posts_on_feature_id"
    t.index ["proposal_votes_count"], name: "index_posts_on_post_votes_count"
    t.index ["title"], name: "post_title_search"
  end

推荐答案

看起来您已向数据库中添加了唯一索引:

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

有了一个唯一的索引,你将只能有一个reportable_typereportable_id相同的记录.很可能您正试图为已经有适度的可报告内容创建适度.

Postgresql相关问答推荐

将real[]数组作为完整的浮点值从postquist返回

带有regex表达式的Postgres SQL

转换失败:(—122.763091,49.04676)转换为地理(位置)""

Psql:Windows 10上奇怪的错误输出编码

Postgres:创建分区需要很长时间

如何将 jackc/pgx 与连接池、上下文、准备好的语句等一起使用

使用Helm设置PostgreSQL配置

JOOQ:数据库版本早于 COCKROACHDB 支持的方言:13.0.0

如何计算每月的出版物数量?

PostgreSQL:如何避免被零除?

查找最小值和最大值

Java - 日期保存为前一天

Postgres/psycopg2 - 插入字符串数组

timezone date_trunc 函数

'active' 标志与否?

当记录包含 json 或字符串的混合时,如何防止 Postgres 中的invalid input syntax for type json

Hibernate 启动很慢

postgres - 比较两个数组

Postgresql 对象 ID 和元组

Ecto Postgres 安装错误密码验证失败