略過至內容略過至搜尋

Active Storage 附加單一

單一附件至模型的表示。

方法
A
B
D
P

執行個體公開方法

附加(可附加)

附加可附加至記錄。

如果記錄已持續並未變更,附件將立即儲存至資料庫。否則,附件將在下一次儲存記錄時儲存至資料庫。

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/jpeg")
person.avatar.attach(avatar_blob) # ActiveStorage::Blob object
# File activestorage/lib/active_storage/attached/one.rb, line 58
def attach(attachable)
  record.public_send("#{name}=", attachable)
  if record.persisted? && !record.changed?
    return if !record.save
  end
  record.public_send("#{name}")
end

附加了嗎()

如果已附加附件,則傳回true

class User < ApplicationRecord
  has_one_attached :avatar
end

User.new.avatar.attached? # => false
# File activestorage/lib/active_storage/attached/one.rb, line 73
def attached?
  attachment.present?
end

附件()

傳回相關附件紀錄。

您不必叫用這個方法存取附件的方法,因為這些方法都在模型層級中可用。

# File activestorage/lib/active_storage/attached/one.rb, line 33
def attachment
  change.present? ? change.attachment : record.public_send("#{name}_attachment")
end

空白嗎()

如果附件未附加,則傳回true

class User < ApplicationRecord
  has_one_attached :avatar
end

User.new.avatar.blank? # => true
# File activestorage/lib/active_storage/attached/one.rb, line 44
def blank?
  !attached?
end

分離

刪除附件,但不過濾,讓 blob 保持原狀。

# File activestorage/lib/active_storage/attached/one.rb, line 25
delegate :detach, to: :detach_one

清除

直接清除附件(即消毀 blob 和附件,並刪除服務中的檔案)。

# File activestorage/lib/active_storage/attached/one.rb, line 13
delegate :purge, to: :purge_one

稍後清除

透過佇列系統清除附件。

# File activestorage/lib/active_storage/attached/one.rb, line 19
delegate :purge_later, to: :purge_one