跳至内容 跳至搜索

Active Storage Attached 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