Skip to content

Commit

Permalink
Delete dependent attachments with record
Browse files Browse the repository at this point in the history
[Matt Jones & George Claghorn]
  • Loading branch information
georgeclaghorn committed Mar 5, 2018
1 parent 8f0b0ee commit 8228d12
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
4 changes: 2 additions & 2 deletions activestorage/lib/active_storage/attached/macros.rb
Expand Up @@ -38,7 +38,7 @@ def #{name}=(attachable)
end
CODE

has_one :"#{name}_attachment", -> { where(name: name) }, class_name: "ActiveStorage::Attachment", as: :record, inverse_of: :record
has_one :"#{name}_attachment", -> { where(name: name) }, class_name: "ActiveStorage::Attachment", as: :record, inverse_of: :record, dependent: :delete
has_one :"#{name}_blob", through: :"#{name}_attachment", class_name: "ActiveStorage::Blob", source: :blob

scope :"with_attached_#{name}", -> { includes("#{name}_attachment": :blob) }
Expand Down Expand Up @@ -83,7 +83,7 @@ def #{name}=(attachables)
end
CODE

has_many :"#{name}_attachments", -> { where(name: name) }, as: :record, class_name: "ActiveStorage::Attachment", inverse_of: :record
has_many :"#{name}_attachments", -> { where(name: name) }, as: :record, class_name: "ActiveStorage::Attachment", inverse_of: :record, dependent: :delete_all
has_many :"#{name}_blobs", through: :"#{name}_attachments", class_name: "ActiveStorage::Blob", source: :blob

scope :"with_attached_#{name}", -> { includes("#{name}_attachments": :blob) }
Expand Down
14 changes: 14 additions & 0 deletions activestorage/test/models/attachments_test.rb
Expand Up @@ -80,6 +80,20 @@ class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
end
end

test "replace independent attached blob" do
@user.cover_photo.attach create_blob(filename: "funky.jpg")

perform_enqueued_jobs do
assert_difference -> { ActiveStorage::Blob.count }, +1 do
assert_no_difference -> { ActiveStorage::Attachment.count } do
@user.cover_photo.attach create_blob(filename: "town.jpg")
end
end
end

assert_equal "town.jpg", @user.cover_photo.filename.to_s
end

test "attach blob to new record" do
user = User.new(name: "Jason")

Expand Down
1 change: 1 addition & 0 deletions activestorage/test/test_helper.rb
Expand Up @@ -65,5 +65,6 @@ def read_image(blob_or_variant)

class User < ActiveRecord::Base
has_one_attached :avatar
has_one_attached :cover_photo, dependent: false
has_many_attached :highlights
end

0 comments on commit 8228d12

Please sign in to comment.