Skip to content

Commit 356916b

Browse files
authored
Merge pull request rails#42224 from abhaynikam/41862-active-storage-has-many-attached-with-nested-attributes
Fixes ActiveStorage#has_many_attached re-creating destroyed attachment
2 parents 67bd5ca + 15d5b75 commit 356916b

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

activestorage/lib/active_storage/attached/changes/create_many.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ class Attached::Changes::CreateMany #:nodoc:
77
def initialize(name, record, attachables)
88
@name, @record, @attachables = name, record, Array(attachables)
99
blobs.each(&:identify_without_saving)
10+
attachments
1011
end
1112

1213
def attachments
@@ -35,13 +36,16 @@ def build_subchange_from(attachable)
3536
ActiveStorage::Attached::Changes::CreateOneOfMany.new(name, record, attachable)
3637
end
3738

38-
3939
def assign_associated_attachments
40-
record.public_send("#{name}_attachments=", attachments)
40+
record.public_send("#{name}_attachments=", persisted_or_new_attachments)
4141
end
4242

4343
def reset_associated_blobs
4444
record.public_send("#{name}_blobs").reset
4545
end
46+
47+
def persisted_or_new_attachments
48+
attachments.select { |attachment| attachment.persisted? || attachment.new_record? }
49+
end
4650
end
4751
end

activestorage/test/models/attached/many_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -648,6 +648,24 @@ def highlights
648648
assert_match(/Cannot find variant :unknown for User#highlights_with_variants/, error.message)
649649
end
650650

651+
test "successfully attaches new blobs and destroys attachments marked for destruction via nested attributes" do
652+
append_on_assign do
653+
town_blob = create_blob(filename: "town.jpg")
654+
@user.highlights.attach(town_blob)
655+
@user.reload
656+
657+
racecar_blob = fixture_file_upload("racecar.jpg")
658+
@user.update(
659+
highlights: [racecar_blob],
660+
highlights_attachments_attributes: [{ id: town_blob.id, _destroy: true }]
661+
)
662+
663+
assert @user.reload.highlights.attached?
664+
assert_equal 1, @user.highlights.count
665+
assert_equal "racecar.jpg", @user.highlights.blobs.first.filename.to_s
666+
end
667+
end
668+
651669
private
652670
def append_on_assign
653671
ActiveStorage.replace_on_assign_to_many, previous = false, ActiveStorage.replace_on_assign_to_many

activestorage/test/test_helper.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ class User < ActiveRecord::Base
128128
has_many_attached :highlights_with_variants do |attachable|
129129
attachable.variant :thumb, resize: "100x100"
130130
end
131+
132+
accepts_nested_attributes_for :highlights_attachments, allow_destroy: true
131133
end
132134

133135
class Group < ActiveRecord::Base

0 commit comments

Comments
 (0)