跳至内容 跳至搜索

Active Storage 附加 Many

代表多个附件到模型的装饰代理对象。

方法
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()

返回所有附加的 Blob。

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

detach

删除关联的附件,但不清除它们,将它们各自的 Blob 保留在原位。

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

purge

直接清除每个关联的附件(即销毁 Blob 和附件并删除服务上的文件)。

# 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