添加dependent: :destroy后仍无法删除Article,违反外键约束
Rails + Fly.io 删除关联文章触发外键约束问题解决
问题
作为Ruby on Rails新手,我在Fly.io上部署了一个简单Web应用,包含Article和Comment两个模型,Article关联多个Comment。当删除带有Comment的Article时,系统提示violate foreign key constraints。在Article模型中添加dependent: :destroy后,问题依旧存在。
排查验证
本地Rails控制台测试destroy操作,能正常完成删除流程:
#<Article:0x00007f6d5f437d20 id: 3, title: "My frist article", body: "This is my first article", created_at: Tue, 04 Jul 2023 01:05:35.148856000 UTC +00:00, updated_at: Tue, 04 Jul 2023 01:05:35.148856000 UTC +00:00> #<Comment:0x00007f6d5f486f88 id: 6, commenter: "Thao", body: "This is a comment from Thao", article_id: 3, created_at: Tue, 04 Jul 2023 01:07:52.288576000 UTC +00:00, updated_at: Tue, 04 Jul 2023 01:07:52.288576000 UTC +00:00> > a1.destroy TRANSACTION (0.1ms) begin transaction Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ? [["article_id", 3]] Comment Destroy (0.2ms) DELETE FROM "comments" WHERE "comments"."id" = ? [["id", 6]] Article Destroy (0.2ms) DELETE FROM "articles" WHERE "articles"."id" = ? [["id", 3]] TRANSACTION (7.2ms) commit transaction => #<Article:0x00007f6d5f437d20 id: 3, title: "My frist article", body: "This is my first article", created_at: Tue, 04 Jul 2023 01:05:35.148856000 UTC +00:00, updated_at: Tue, 04 Jul 2023 01:05:35.148856000 UTC +00:00>
日志显示事务会先加载关联的Comment,删除后再删除Article,符合dependent: :destroy的预期行为。
解决方法
重新部署Fly.io应用后,问题彻底解决。
原因
Fly.io平台未自动更新部署的代码,添加dependent: :destroy后的修改没有同步到线上环境。
相关代码
模型代码
class Article < ApplicationRecord has_many :comments, dependent: :destroy end class Comment < ApplicationRecord belongs_to :article end
Schema文件
ActiveRecord::Schema[7.0].define(version: 2023_06_22_082322) do create_table "articles", force: :cascade do |t| t.string "title" t.text "body" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "comments", force: :cascade do |t| t.string "commenter" t.text "body" t.integer "article_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["article_id"], name: "index_comments_on_article_id" end add_foreign_key "comments", "articles" end
内容的提问来源于stack exchange,提问作者Thảo Nguyễn
相关产品推荐
相关产品推荐

