跳至內容 跳至搜尋

Active Storage Attached Many

裝飾的代理物件,用來表示多個附加至特定 model 的檔案。

方法
A
B
D
P

實體公共方法

attach(*attachables)

將一個或多個 attachables 附加至記錄中。

如果記錄已持久化且未變更,這些附件會立即儲存至資料庫中。否則,當下一次儲存記錄時,這些附件才會儲存到資料庫。

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/jpeg")
document.images.attach([ first_blob, second_blob ])
# File activestorage/lib/active_storage/attached/many.rb, line 51
def attach(*attachables)
  record.public_send("#{name}=", blobs + attachables.flatten)
  if record.persisted? && !record.changed?
    return if !record.save
  end
  record.public_send("#{name}")
end

attached?()

如果已建立任何附件,則回傳 true。

class Gallery < ApplicationRecord
  has_many_attached :photos
end

Gallery.new.photos.attached? # => false
# File activestorage/lib/active_storage/attached/many.rb, line 66
def attached?
  attachments.any?
end

attachments()

回傳所有關聯的附件記錄。

在此代理物件上呼叫的所有方法(未在此列出),都將自動委派至 attachments

# File activestorage/lib/active_storage/attached/many.rb, line 32
def attachments
  change.present? ? change.attachments : record.public_send("#{name}_attachments")
end

blobs()

回傳所有已附加的二進位大物件。

# File activestorage/lib/active_storage/attached/many.rb, line 37
def blobs
  change.present? ? change.blobs : record.public_send("#{name}_blobs")
end

detach

刪除關聯的附件,但不清除它們,讓各自的二進位大物件保持原狀。

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

purge

直接清除每個關聯的附件(也就是銷毀二進位大物件和附件,並在服務上刪除檔案)。

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

purge_later

透過排隊系統,清除每個相關的附件。

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