aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage/lib/active_storage/attached/many.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activestorage/lib/active_storage/attached/many.rb')
-rw-r--r--activestorage/lib/active_storage/attached/many.rb21
1 files changed, 14 insertions, 7 deletions
diff --git a/activestorage/lib/active_storage/attached/many.rb b/activestorage/lib/active_storage/attached/many.rb
index 073cc013d8..25f88284df 100644
--- a/activestorage/lib/active_storage/attached/many.rb
+++ b/activestorage/lib/active_storage/attached/many.rb
@@ -12,19 +12,26 @@ module ActiveStorage
change.present? ? change.attachments : record.public_send("#{name}_attachments")
end
- # Associates one or several attachments with the current record, saving them to the database.
+ # Returns all attached blobs.
+ def blobs
+ change.present? ? change.blobs : record.public_send("#{name}_blobs")
+ end
+
+ # Attaches one or more +attachables+ to the record.
+ #
+ # If the record is persisted and unchanged, the attachments are saved to
+ # the database immediately. Otherwise, they'll be saved to the DB when the
+ # record is next saved.
#
# document.images.attach(params[:images]) # Array of ActionDispatch::Http::UploadedFile objects
# document.images.attach(params[:signed_blob_id]) # Signed reference to blob from direct upload
# document.images.attach(io: File.open("/path/to/racecar.jpg"), filename: "racecar.jpg", content_type: "image/jpg")
# document.images.attach([ first_blob, second_blob ])
def attach(*attachables)
- attachables.flatten.collect do |attachable|
- if record.new_record?
- attachments.build(record: record, blob: create_blob_from(attachable))
- else
- attachments.create!(record: record, blob: create_blob_from(attachable))
- end
+ if record.persisted? && !record.changed?
+ record.update(name => blobs + attachables.flatten)
+ else
+ record.public_send("#{name}=", blobs + attachables.flatten)
end
end