mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #45345 from santib/fix-attachments-in-transaction
Fix #45339 attachments for new record within transaction Co-authored-by: Jorge Manrubia <jorge@hey.com>
This commit is contained in:
commit
ed3130a41d
2 changed files with 16 additions and 10 deletions
|
@ -47,16 +47,9 @@ module ActiveStorage
|
|||
# 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.
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue