I'm new to Ruby on Rails and I'm trying to build a simple web application.
- I have an 'article' model and a 'comment' model
- The 'article' can have many 'comments'. I deployed my web on fly.io. When I create an article and add comment to that article, I can not delete the article and the error said that 'violate foreign key constraints'. So I thought adding "dependent: :destroy" would solve the problem but it's not, still the same error. Did I miss something? Do I need to run any migration ? Below is part of my code.
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
end
class Comment < ApplicationRecord
belongs_to :article
end
UPDATED: Below is my schema file
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
UPDATED: I tried to reproduce the problem in rails console
- I created
a1
article andc1
comment belongs to that article, and when I deleteda1
with.destroy
, everything worked fine. Below is my code:
#<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>
UPDATED: I deployed my web app again and the problem is fixed. I thought fly.io would automatically update my code but it's not. Thanks everyone for your help.