删除记录违反外键约束

时间:2019-07-10 07:04:39

标签: ruby-on-rails ruby

我有一个通知表,其中存储了多个模型的ID,因此用户会收到有关这些通知的操作的通知(有人在您的文章上发表了评论)。通知并不“属于”任何东西,而是要去的用户,不过,它只是引用事物的ID。因此,例如,现在每当我尝试删除文章时,都会出现错误:

ActiveRecord::InvalidForeignKey (PG::ForeignKeyViolation: ERROR:  update or delete on table "comments" violates foreign key constraint "fk_rails_9268535f02" on table "notifications"

如何设置它以删除所有引用的通知?

我的通知数据库模式:

create_table "notifications", force: :cascade do |t|
t.integer  "recipient_id"
t.integer  "notified_by_id"
t.integer  "glip_id"
t.integer  "article_id"
t.integer  "group_id"
t.integer  "post_id"
t.integer  "comment_id"
t.integer  "notation_id"
t.integer  "response_id"
t.integer  "remark_id"
t.integer  "conversation_id"
t.integer  "message_id"
t.boolean  "read",              default: false
t.datetime "created_at",                        null: false
t.datetime "updated_at",                        null: false
t.integer  "notification_type"
t.index ["article_id"], name: "index_notifications_on_article_id"
t.index ["comment_id"], name: "index_notifications_on_comment_id"
t.index ["conversation_id"], name: "index_notifications_on_conversation_id"
t.index ["glip_id"], name: "index_notifications_on_glip_id"
t.index ["group_id"], name: "index_notifications_on_group_id"
t.index ["message_id"], name: "index_notifications_on_message_id"
t.index ["notation_id"], name: "index_notifications_on_notation_id"
t.index ["notified_by_id"], name: "index_notifications_on_notified_by_id"
t.index ["post_id"], name: "index_notifications_on_post_id"
t.index ["recipient_id"], name: "index_notifications_on_recipient_id"
t.index ["remark_id"], name: "index_notifications_on_remark_id"
t.index ["response_id"], name: "index_notifications_on_response_id"

结束

我的通知模型:

class Notification < ApplicationRecord
  enum notification_type: { comment: 0, notation: 1, message: 2, feature: 3, marked_helpful: 4,
                            participation: 5, response: 6, remark: 7, follow: 8, unfollow: 9 }
  enum read: { read: true, unread: false }
  belongs_to :notified_by, class_name: 'User'
end

2 个答案:

答案 0 :(得分:2)

您的User应该使用:dependent option

class User < ApplicationRecord
  # ...
  has_many :notifications, foreign_key: :notified_by_id, dependent: :destroy
end

如果您在关联的:foreign_key端使用了:class_name,则belongs_to should also be specified

现在,当您删除User时,所有引用它们的通知也将被删除。

您可以对Article或引用的任何其他模型重复相同的过程。

答案 1 :(得分:2)

可能是由于删除article时同时删除了相关的comments,并且在数据库级别的注释和通知表之间存在外键约束,导致无法删除它。 / p>

我的建议是,如果您希望删除关联的通知以及评论,请在dependent: :destroy模型中添加Comment

class Comment < ApplicationRecord
  has_many :notifications, dependent: destroy
end

如果您希望在删除评论时不删除通知

class Comment < ApplicationRecord
  has_many :notifications, dependent: :nullify
end

更多细节请看 dependet :destroy & dependent: :nullify

之间的区别
相关问题