Skip to content

Commit

Permalink
Fix #45339 attachments for new record within transaction
Browse files Browse the repository at this point in the history
Co-authored-by: Juan Eduardo Roig <jeroig@gmail.com>
  • Loading branch information
santib and jeroig committed Jun 17, 2022
1 parent 54d866b commit 75d58c8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
13 changes: 3 additions & 10 deletions activestorage/lib/active_storage/attached/many.rb
Expand Up @@ -47,16 +47,9 @@ def blobs
# document.images.attach(io: File.open("/path/to/racecar.jpg"), filename: "racecar.jpg", content_type: "image/jpeg")
# document.images.attach([ first_blob, second_blob ])
def attach(*attachables)
if record.persisted? && !record.changed?
record.public_send("#{name}=", blobs + attachables.flatten)
if record.save
record.public_send("#{name}")
else
false
end
else
record.public_send("#{name}=", (change&.attachables || blobs) + attachables.flatten)
end
record.public_send("#{name}=", blobs + attachables.flatten)
return false if record.persisted? && !record.changed? && !record.save
record.public_send("#{name}")
end

# Returns true if any attachments have been made.
Expand Down
13 changes: 13 additions & 0 deletions activestorage/test/models/attached/many_test.rb
Expand Up @@ -181,6 +181,19 @@ class ActiveStorage::ManyAttachedTest < ActiveSupport::TestCase
assert ActiveStorage::Blob.service.exist?(@user.highlights.third.key)
end

test "attaching many new blobs within a transaction on a new record uploads all the files" do
user = User.create!(name: "John") do |user|
user.highlights.attach(io: StringIO.new("STUFF"), filename: "funky.jpg", content_type: "image/jpeg")
user.highlights.attach(io: StringIO.new("THINGS"), filename: "town.jpg", content_type: "image/jpeg")
end

assert_equal 2, user.highlights.count
assert_equal "funky.jpg", user.highlights.first.filename.to_s
assert_equal "town.jpg", user.highlights.second.filename.to_s
assert ActiveStorage::Blob.service.exist?(user.highlights.first.key)
assert ActiveStorage::Blob.service.exist?(user.highlights.second.key)
end

test "attaching new blobs within a transaction create the exact amount of records" do
assert_difference -> { ActiveStorage::Blob.count }, +2 do
ActiveRecord::Base.transaction do
Expand Down

0 comments on commit 75d58c8

Please sign in to comment.