From be0d22a8e1465a4a30f262ac348edf87daee03e9 Mon Sep 17 00:00:00 2001 From: bogdanvlviv Date: Sun, 16 Sep 2018 21:52:42 +0300 Subject: [PATCH] Raise `ActiveRecord::InvalidForeignKey` in `before_destroy` for a blob if attachments exist The issue #32584 was fixed in #33405 by adding foreign key constraint to the `active_storage_attachments` table for blobs. This commit implements fix on app-level in order to ensure that users can't delete a blob with attachments even if they don't have the foreign key constraint. See a related discussion in the Campfire: https://3.basecamp.com/3076981/buckets/24956/chats/12416418@1236718899 Note that, we should backport it to `5-2-stable` too. Related to #33405 --- activestorage/app/models/active_storage/blob.rb | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/activestorage/app/models/active_storage/blob.rb b/activestorage/app/models/active_storage/blob.rb index e7f2615b0f..53aa9f0237 100644 --- a/activestorage/app/models/active_storage/blob.rb +++ b/activestorage/app/models/active_storage/blob.rb @@ -35,6 +35,10 @@ class ActiveStorage::Blob < ActiveRecord::Base scope :unattached, -> { left_joins(:attachments).where(ActiveStorage::Attachment.table_name => { blob_id: nil }) } + before_destroy(prepend: true) do + raise ActiveRecord::InvalidForeignKey if attachments.exists? + end + class << self # You can used the signed ID of a blob to refer to it on the client side without fear of tampering. # This is particularly helpful for direct uploads where the client-side needs to refer to the blob