首页 > 解决方案 > Rails admin gem 显示 s3 附件,即 IMAGES/PDF/DOCS/XLSX

问题描述

我将 rails_admin gem 用于后端管理端的 rails api 应用程序。

我正在使用带有 active_storage 的 rails 6 并将附件存储在 S3 上。

在管理方面,我需要显示可能是图像或文件的附件列表。

我的问题是如何以索引方法显示那些,我需要显示图像然后在 pdf/docs 中显示什么,我需要显示 s3 的唯一链接吗?

目前,看起来这些损坏的图像是图像,而另一个是文件

在此处输入图像描述

我的模型

  class Attachment < AttachmentBlock::ApplicationRecord
    self.table_name = :attachments
    include Wisper::Publisher

    has_one_attached :attachment
    belongs_to :account, class_name: 'AccountBlock::Account'
    has_and_belongs_to_many :orders , class_name: 'BxBlockOrdermanagement::Order'
    scope :not_expired, -> {where('is_expired = ?',false)}
  end

我应该在这里使用什么来列出用户上传的附件?
如何检查附件类型,然后它的图像是否显示图像,如果它是文件,则显示来自 s3 的文件 url?

谢谢。

标签: ruby-on-railsrails-admin

解决方案


你的问题分为两部分:

要在 rails admin 上添加侧边菜单的链接,您需要定义模型,因此如果您想要为所有“pdf”类型的附件建立索引,您可以使用 rails STI(单表继承)或定义自定义 default_scope,如下所示:

class ImageAttachment < Attachment
  def self.default_scope
   where('attachments.attachment LIKE ?', '%png') }
  end
end

要自定义每个单独的附件记录的行,您需要为模型 rails 管理配置上的字段定义该行为。

例如,您可以将此代码块放在 ImageAttachment 类中。

class ImageAttachment < Attachment
  def self.default_scope
   where('attachments.attachment LIKE ?', '%png') }
  end

  rails_admin do
    configure :attachment do
      view = bindings[:view]
      attachment  = bindings[:object]

      if view
        view.content_tag(:img, attachment.attachment.url)
      else
        ''
      end
    end

    list do 
      field :attachment
    end
  end
end

正如您在附件字段配置块中看到的那样,您可以访问附件对象,当然还有它的所有方法,您可以确定附件的类型并进行一些特殊的 html 渲染。


推荐阅读