跳至内容 跳至搜索

Active Storage 附加 One

表示模型的单个附件。

方法
A
B
D
P

实例公共方法

attach(attachable)

attachable 附加到记录。

如果记录已持久化且未更改,则附件将立即保存到数据库中。否则,它将在下次保存记录时保存到数据库中。

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

attached?()

如果已进行附件,则返回 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

attachment()

返回关联的附件记录。

您不必调用此方法来访问附件的方法,因为它们都可以在模型级别使用。

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

blank?()

如果未附加附件,则返回 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

detach

删除附件而不清除它,使其 blob 保持在原位。

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

purge

直接清除附件(即销毁 blob 和附件并删除服务上的文件)。

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

purge_later

通过排队系统清除附件。

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