我正在尝试预览我上传的PDF文件和图像文件:
class Document < ApplicationRecord
belongs_to :resourceable, :polymorphic => true
has_one_attached :file
end
我尝试使用.preview和.representation方法将上传的图像或pdf的预览显示为缩略图。
@document.file.preview(resize_to_limit: [100, 100])
ActiveStorage::UnpreviewableError: ActiveStorage::UnpreviewableError
>>> image_tag(@document.file.representation(resize: '500x500'))
ArgumentError: Can't resolve image into URL: undefined method `to_model' for #<ActiveStorage::Variant:0x00007fe39e809768>
document.file.representable?
和document.file.previewable?
在某些文档中。想知道这些方法做什么?有时我可以表示为true,但可以预览为false。
答案 0 :(得分:0)
从Rails 5.2开始,image_tag
助手需要您传递一个URL。在猜测通过什么之前。
要从您的活动存储版本中传递网址,请执行以下操作:
image_tag(main_app.rails_representation_url(
@document.file.variant(resize: '500x500'))
) if @document.file.attached?
根据docs,图片不可预览,而PDF则无法预览。
要检查文档是否具有预览功能,请使用previewable?
方法:
image_tag(main_app.rails_representation_url(
@document.try(@document.previewable? ? :preview : :variant, resize: '500x500')
) if @document.file.attached?