class ActiveStorage::Attached::One
Representation of a single attachment to a model.
def attach(attachable)
person.avatar.attach(io: File.open("/path/to/face.jpg"), filename: "face.jpg", content_type: "image/jpg")
person.avatar.attach(params[:signed_blob_id]) # Signed reference to blob from direct upload
person.avatar.attach(params[:avatar]) # ActionDispatch::Http::UploadedFile object
record is next saved.
the database immediately. Otherwise, it'll be saved to the DB when the
If the record is persisted and unchanged, the attachment is saved to
Attaches an +attachable+ to the record.
def attach(attachable) if record.persisted? && !record.changed? record.update(name => attachable) else record.public_send("#{name}=", attachable) end end
def attached?
end
has_one_attached :avatar
class User < ActiveRecord::Base
Returns +true+ if an attachment has been made.
def attached? attachment.present? end
def attachment
You don't have to call this method to access the attachment's methods as
Returns the associated attachment record.
def attachment change.present? ? change.attachment : record.public_send("#{name}_attachment") end
def blank?
def blank? !attached? end
def detach
def detach if attached? attachment.delete write_attachment nil end end
def purge
Directly purges the attachment (i.e. destroys the blob and
def purge if attached? attachment.purge write_attachment nil end end
def purge_later
def purge_later if attached? attachment.purge_later write_attachment nil end end
def write_attachment(attachment)
def write_attachment(attachment) record.public_send("#{name}_attachment=", attachment) end