deep foreign key constraint fails
Stajor opened this issue · 2 comments
I get an error when try to delete row with deep foreign key.
I have three models:
Community
has_many :posts, dependent: :delete_all
Post
belongs_to :community
has_many :attachments, dependent: :delete_all
Attachment
belongs_to :post
on @community.destroy have error
ActiveRecord::StatementInvalid (Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails (attachments
, CONSTRAINT attachments_post_id_fk
FOREIGN KEY (post_id
) REFERENCES posts
(id
)): DELETE FROM posts
WHERE posts
.community_id
= 1):
It is deleting all posts
with a SQL query, and that never runs a delete on the attachments. Basically, you cannot use Community.has_many :posts, dependent: :delete_all
, and must use Community.has_many :posts, dependent: :destroy
instead.
You can keep using the :delete_all
option on Post.has_many :attachments
.
I closed this because I cannot change anything in this gem to fix this.