aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage/lib/active_storage/attached/one.rb
diff options
context:
space:
mode:
authorGeorge Claghorn <george@basecamp.com>2018-07-13 13:29:33 -0400
committerGeorge Claghorn <george@basecamp.com>2018-07-13 13:29:33 -0400
commit28db8ba60e726d695cf35710cc43ea45966464e9 (patch)
treee8e0306d761f10262d60f9021d47745a831574f1 /activestorage/lib/active_storage/attached/one.rb
parentd20d6c732613dcc7276cb57d451e2a3bf573df19 (diff)
downloadrails-28db8ba60e726d695cf35710cc43ea45966464e9.tar.gz
rails-28db8ba60e726d695cf35710cc43ea45966464e9.tar.bz2
rails-28db8ba60e726d695cf35710cc43ea45966464e9.zip
Implement ActiveStorage::Attached::{One,Many}#attach in terms of changes
Diffstat (limited to 'activestorage/lib/active_storage/attached/one.rb')
-rw-r--r--activestorage/lib/active_storage/attached/one.rb20
1 files changed, 9 insertions, 11 deletions
diff --git a/activestorage/lib/active_storage/attached/one.rb b/activestorage/lib/active_storage/attached/one.rb
index 4a6bb1ffaa..c039226fcd 100644
--- a/activestorage/lib/active_storage/attached/one.rb
+++ b/activestorage/lib/active_storage/attached/one.rb
@@ -17,17 +17,21 @@ module ActiveStorage
!attached?
end
- # Associates a given attachment with the current record, saving it to the database.
+ # Attaches an +attachable+ to the record.
+ #
+ # If the record is persisted and unchanged, the attachment is saved to
+ # the database immediately. Otherwise, it'll be saved to the DB when the
+ # record is next saved.
#
# person.avatar.attach(params[:avatar]) # ActionDispatch::Http::UploadedFile object
# person.avatar.attach(params[:signed_blob_id]) # Signed reference to blob from direct upload
# person.avatar.attach(io: File.open("/path/to/face.jpg"), filename: "face.jpg", content_type: "image/jpg")
# person.avatar.attach(avatar_blob) # ActiveStorage::Blob object
def attach(attachable)
- new_blob = create_blob_from(attachable)
-
- if !attached? || new_blob != blob
- write_attachment build_attachment(blob: new_blob)
+ if record.persisted? && !record.changed?
+ record.update(name => attachable)
+ else
+ record.public_send("#{name}=", attachable)
end
end
@@ -68,12 +72,6 @@ module ActiveStorage
end
private
- delegate :transaction, to: :record
-
- def build_attachment(blob:)
- Attachment.new(record: record, name: name, blob: blob)
- end
-
def write_attachment(attachment)
record.public_send("#{name}_attachment=", attachment)
end