From 32438ed64fea7dbe52ea0898be3d4276e63baa78 Mon Sep 17 00:00:00 2001 From: Abhishek Chandrasekhar Date: Wed, 20 Feb 2019 23:37:10 -0500 Subject: [ActiveStorage] Ensure that the `_blob` association is properly loaded when attaching `::One` Consider a model with `One` and `Many` attachments configured: class User < ActiveRecord::Base has_one_attached :avatar has_many_attached :highlights end === One Attachment After attaching `One` attachment (`:avatar`), we can see that the associated `_blob` record (`:avatar_blob`) still returns as `nil`. user.avatar.attach(blob) user.avatar_attachment.present? => true user.avatar_blob.present? => false # Incorrect! This is a false negative. It happens because after the attachment and blob are built: 1. The record already has its `_blob` association loaded, as `nil` 2. the `::Attachment` is associated with the record but the `::Blob` only gets associated with the `::Attachment`, not the record itself In reality, the blob does in fact exist. We can verify this as follows: user.avatar.attach(blob) user.avatar_attachment.blob.present? => true # Blob does exist! The fix in this change is to simply assign the `::Blob` when assigning the `::Attachment`. After this fix is applied, we correctly observe: user.avatar.attach(blob) user.avatar_attachment.present? => true user.avatar_blob.present? => true # Woohoo! === Many Attachments We don't see this issue with `Many` attachments because the `_blob` association is already loaded as part of attaching more/newer blobs. user.highlights.attach(blob) user.highlights_attachments.any? => true user.highlights_blobs.any? => true --- activestorage/lib/active_storage/attached/changes/create_one.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activestorage/lib') diff --git a/activestorage/lib/active_storage/attached/changes/create_one.rb b/activestorage/lib/active_storage/attached/changes/create_one.rb index 5812fd2b08..89cccfb58a 100644 --- a/activestorage/lib/active_storage/attached/changes/create_one.rb +++ b/activestorage/lib/active_storage/attached/changes/create_one.rb @@ -30,6 +30,7 @@ module ActiveStorage def save record.public_send("#{name}_attachment=", attachment) + record.public_send("#{name}_blob=", blob) end private -- cgit v1.2.3