ActiveAdmin 模糊表单中的错误消息

问题描述 投票:0回答:1

我们在使用 ImageMagick 时遇到了一个无法排序的问题,但我们需要通过上传图像的表单来向用户隐藏与其相关的错误。我想出了一个蛮力操作覆盖,它适用于更新,但会破坏创建。我知道这并不理想,但我很难破译源代码。有更好的办法吗?

controller do
    before_action :set_topic,
                  only: [:create, :update]

    def create
      unless create_or_update_topic
        super
      end
    end

    def update
      unless create_or_update_topic
        super
      end
    end

    private

    def set_topic
      topic_id = params[:id]
      @topic = topic_id.present? ? Topic.find(topic_id) : nil
    end

    def create_or_update_topic
      begin
        if @topic.nil?
          @topic = Topic.create!(permitted_params[:topic])
        else
          @topic.update!(permitted_params[:topic])
        end

        respond_to do |format|
          format.html { redirect_to admin_topic_path(@topic), notice: "Topic was successfully #{params[:action] === 'create' ? 'created' : 'updated'}." }
        end
      rescue
        if @topic.errors.messages.values.flatten.any? {|v| v.include?('Paperclip::Errors'||'ImageMagick')}
          error_message = "There was an issue with uploading your image file."
        else
          return false
        end
        respond_to do |format|
          if params[:action] === 'update'
            format.html { redirect_to edit_admin_topic_path(@topic), flash: { error:  error_message} }
          else
            format.html { redirect_to new_admin_topic_path, flash: { error:  error_message} }
          end
        end
      end
    end
  end

覆盖操作,捕获我想要掩盖的错误,重定向到带有闪存消息的表单。如果我关心的错误不存在,请推迟到

super
,保留内置错误处理。

可在提交损坏的图像文件时进行更新,但在从创建表单执行相同操作时会响应 500 错误。

ruby-on-rails imagemagick paperclip activeadmin
1个回答
0
投票

不知道我是如何在 ActiveAdmin 自述文件中忽略这一点的,但以下正是我所需要的,它仍然是实现我模糊特定 ImageMagick 错误的目标的一种强力方法,但它与 AA 的内置功能配合得很好 -在错误处理中:

controller do
    def create(_options={}, &block)
      create! do |success, failure|
        yield(success, failure) if block

        resource.errors.messages.each do |k,v|
          if v.include?("Paperclip::Errors::NotIdentifiedByImageMagickError")
            resource.errors.messages[k] = "There was an issue with uploading your image file."
          end
        end

        failure.html { render :new }
      end
    end

    def update(_options={}, &block)
    update! do |success, failure|
      yield(success, failure) if block

      resource.errors.messages.each do |k,v|
          if v.include?("Paperclip::Errors::NotIdentifiedByImageMagickError")
            resource.errors.messages[k] = "There was an issue with uploading your image file."
          end
        end

        failure.html { render :edit }
      end
    end
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.