Ruby 当销毁失败时,我可以在active admin中有一条flash消息吗?

Ruby 当销毁失败时,我可以在active admin中有一条flash消息吗?,ruby,activeadmin,Ruby,Activeadmin,在我的应用程序中,某些资源无法销毁。所以我这样写我的模型: before_destroy :destroy_check def destroy_check if some_reason? errors.add(:base, 'cannot destroy this resource!') end errors.blank? end 然后,当我在ActiveAdmin中单击destroy按钮时,没有显示任何内容:没有错误,没有消息,记录也没有被真正销毁。销毁失败时,如何显示错

在我的应用程序中,某些资源无法销毁。所以我这样写我的模型:

before_destroy :destroy_check
def destroy_check
  if some_reason?
    errors.add(:base, 'cannot destroy this resource!')
  end
  errors.blank?
end

然后,当我在ActiveAdmin中单击destroy按钮时,没有显示任何内容:没有错误,没有消息,记录也没有被真正销毁。销毁失败时,如何显示错误消息?

如果您希望成为尚未从活动管理员中删除的资源:

ActiveAdmin.register SomeModel do
  controller do        
    def destroy
      flash[:notice] = 'Cant delete this!'
      redirect_to :back
    end        
  end
end
或删除操作:

ActiveAdmin.register SomeModel do
  actions :all, except: [:destroy]
end

在销毁之前,首先使用模型的
回调检查记录是否可以销毁(如果学生已登录,则在此处):


我发现这可以在ActiveAdmin中通过I18n翻译和定制控制器中的响应程序来实现

将方法#interpolation_选项添加到初始化器中的ActiveAdmin::BaseController:

# config/initializers/active_admin.rb
class ActiveAdmin::BaseController
  private

  def interpolation_options
    options = {}

    options[:resource_errors] =
      if resource && resource.errors.any?
        "#{resource.errors.full_messages.to_sentence}."
      else
        ""
      end

    options
  end
end
然后覆盖区域设置文件中销毁警报消息的翻译:

# config/locales/en.yml
en:
  flash:
    actions:
      destroy:
        alert: "%{resource_name} could not be destroyed. %{resource_errors}"

添加销毁功能没问题,我会试试。我不能排除所有销毁操作,因为有些资源允许销毁,但有些资源不允许。这里的第二位代码似乎破坏了rails自动重新加载?如果我更改代码并点击任何页面,我会得到以下错误
nil的未定义方法“controller”:NilClass提取源代码(第14行附近):def run_registration_block(&block)old_run_registration_block(&block)instance_exec{after_destroy:check_model_errors}结束
,突出显示实例执行行。这会发生在其他人身上吗?
# config/initializers/active_admin.rb
class ActiveAdmin::BaseController
  private

  def interpolation_options
    options = {}

    options[:resource_errors] =
      if resource && resource.errors.any?
        "#{resource.errors.full_messages.to_sentence}."
      else
        ""
      end

    options
  end
end
# config/locales/en.yml
en:
  flash:
    actions:
      destroy:
        alert: "%{resource_name} could not be destroyed. %{resource_errors}"