跳至内容 跳至搜索

Active Storage 关联(多个)

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

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