Add ActiveStorage::Blob.unattached scope

This commit is contained in:
fatkodima 2018-02-12 22:09:52 +02:00
parent 18b13d768f
commit 0c463f50ea
2 changed files with 19 additions and 0 deletions

View File

@ -27,6 +27,8 @@ class ActiveStorage::Blob < ActiveRecord::Base
has_many :attachments
scope :unattached, -> { left_joins(:attachments).where(ActiveStorage::Attachment.table_name => { blob_id: nil }) }
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

View File

@ -7,6 +7,23 @@ require "active_support/testing/method_call_assertions"
class ActiveStorage::BlobTest < ActiveSupport::TestCase
include ActiveSupport::Testing::MethodCallAssertions
test ".unattached scope returns not attached blobs" do
class UserWithHasOneAttachedDependentFalse < User
has_one_attached :avatar, dependent: false
end
ActiveStorage::Blob.delete_all
blob_1 = create_blob filename: "funky.jpg"
blob_2 = create_blob filename: "town.jpg"
user = UserWithHasOneAttachedDependentFalse.create!
user.avatar.attach blob_1
assert_equal [blob_2], ActiveStorage::Blob.unattached
user.destroy
assert_equal [blob_1, blob_2].map(&:id).sort, ActiveStorage::Blob.unattached.pluck(:id).sort
end
test "create after upload sets byte size and checksum" do
data = "Hello world!"
blob = create_blob data: data