上传新图片后,如何在Actveadmin中删除或更新之前上传的图片?

How to delete or update the previously uploaded image in Actveadmin after uploading a new image?

基本上,在我的表单中,我正在上传图片,并且可以选择在图片已存在时删除图片。但是我想在上传新图片后从我的磁盘中删除图像。如何在 ActiveAdmin

中做到这一点

管理员模型:

f.inputs do
     
      f.input :image, as: :file, hint: (f.object.image.attached?) ? image_tag(url_for(f.object.image)) : content_tag(:span, "JPG oder PNG")
      if f.object.image.present?
        f.input :remove_image, as: :boolean, required: false, label: "Remove"
      end
end

f.actions

型号:

  belongs_to :parent
  default_scope { order(:position) }
  has_one_attached :image, :dependent => :destroy
  attr_writer :remove_image
  validates :image, blob: { content_type: ['image/png', 'image/jpg', 'image/jpeg'] }
  before_validation :image_delete

  def remove_image
    @remove_image || false
  end

  def image_delete
    self.image.purge if self.remove_image == '1'
  end

好吧,我会发布我的答案,以防将来对某人有所帮助。这很容易,但有点棘手。我不得不稍微调整一下我的模型。

已移除before_validation

型号:

      belongs_to :parent
      default_scope { order(:position) }
      has_one_attached :image, :dependent => :destroy
      attr_writer :remove_image
      validates :image, blob: { content_type: ['image/png', 'image/jpg', 'image/jpeg'] }

     def remove_image
      @remove_image || false
     end

controller 内的管理模型中,方法 update 在表单提交时被调用。只需删除初始图像并保存 params

中的新图像
def update

      v = Model.find( params[:id] )

      if params[:model][:image].present?
        v.image.purge
        v.image = params[:model][:image]
      end

      if params[:model][:remove_image].present? && params[:model][:remove_image] == '1'
          v.image.purge
      end

      if v.save
        redirect_to model_path(v)
      else
        render :edit
      end

    end

因为我也单独删除图像remove_image被使用。 更多来源:https://spin.atomicobject.com/2016/01/29/uploading-files-active-admin/