Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit multiple attached images using ActiveStorage `has_many_attached` in ActiveAdmin

I have a simple model that can have multiple images attached via ActiveStorage handling the file storage.

I am using ActiveAdmin to edit my model and to upload/attach the images - so far no problems.

The problem is, when I want to edit my model, and add new images, then the previous ones are deleted, and only the new ones added.

I can do a preview of already attached images, and could also delete them separately, but how do I achieve, that by uploading new images, the old ones are NOT deleted?

My model:

class Post < ActiveRecord::Base
  has_many_attached :images
end

My ActiveAdmin page:

ActiveAdmin.register AdminPost do
  permit_params images:[]

  form do |f|
    f.input :images, as: :file, input_html: { multiple: true }

    if @resource.images.exists?
      @resource.images.map do |m|
        para image_tag m
      end
    end
  end 
end
like image 352
Asped Avatar asked May 21 '20 11:05

Asped


People also ask

How does active storage handle image variants?

If a variant is requested, Active Storage will automatically apply transformations depending on the image's format: Content types that are variable (as dictated by config.active_storage.variable_content_types ) and not considered web images (as dictated by config.active_storage.web_image_content_types ), will be converted to PNG.

What is active storage and how does it work?

It comes with a local disk-based service for development and testing and supports mirroring files to subordinate services for backups and migrations. Using Active Storage, an application can transform image uploads or generate image representations of non-image uploads like PDFs and videos, and extract metadata from arbitrary files.

Why can’t active storage determine the content type of a file?

If you don’t provide a content type and Active Storage can’t determine the file’s content type automatically, it defaults to application/octet-stream. To remove an attachment from a model, call purge on the attachment.

What permissions do I need to use active storage?

The core features of Active Storage require the following permissions: s3:ListBucket, s3:PutObject, s3:GetObject, and s3:DeleteObject. Public access additionally requires s3:PutObjectAcl. If you have additional upload options configured such as setting ACLs then additional permissions may be required.


1 Answers

Assuming you are using rails 6.0+; you can solve this by adding following code in to your environments (i.e - development.rb ) https://github.com/rails/rails/issues/35817#issuecomment-628654948

config.active_storage.replace_on_assign_to_many = false

in your form,

form do |f|
 f.input :images, as: :file, input_html: { multiple: true }
 f.object.images.each do |image|
  span image_tag(image)
 end
end 
like image 180
roshiend Avatar answered Oct 02 '22 11:10

roshiend