Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

Rails admin gem showing s3 attachments which is IMAGES/PDF/DOCS/XLSX

I am using rails_admin gem for the rails api application for the backend admin side.

I am using rails 6 with active_storage and storing attachments on the S3.

On the admin side, I need to display the list of attachments which might be images or files anything.

My question is How to show those in index method, do I need to show images then what to show in pdf/docs, do I need to show the only the link of s3?

currently, it looks like these broken images are the images and other one were files

enter image description here

My model

  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

What should I use here to list the attachment that the user upload?
how to check the attachment type and then if its image then shows the image and if it files then show file url from s3?

thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yours is a two part question:

To add links to the side menu on rails admin you need to define models so if you wanted an index for all the attachments of type 'pdf' you could use rails STI (single table inheritance) or define a custom default_scope like this:

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

To customize the row of each individual attachment record you need to defined that behavior for the field on the model rails admin config.

For example you can put this block of code inside your ImageAttachment class.

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

As you can see inside the attachment field configuration block you have access to the attachment object and of course all its methods, you can determine the type of attachment and do some special html rendering.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...