操作策略 - 定义异常消息

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

我正在尝试将 actionpolicy 集成到 Rails 7.1 应用程序中,但我很难理解如何定义自定义异常消息。

我的代码非常基础

class InvestigationReviewsController < ApplicationController
  def new
    @investigation = Investigation.find(params[:investigation_id])
    authorize! @investigation, with: InvestigationReviewPolicy
  end
  ...
end
class InvestigationReviewPolicy < ApplicationPolicy
  def new?
    record.state == "completed"
  end
end
class ApplicationController < ActionController::Base
  rescue_from ActionPolicy::Unauthorized do |ex|
    p "details: #{ex.result.reasons.details}"
    p "full messages: #{ex.result.reasons.full_messages}" 
  end
  ...
end

这就是我的日志的样子

web |   ↳ app/controllers/investigation_reviews_controller.rb:11:in `new'
web | "details: {}"
web | "full messages: []"

我想向用户显示一条消息,说明调查处于错误状态。

您对如何实现这一目标有什么想法吗?

ruby-on-rails authorization
1个回答
0
投票

来自文档

例如,给定一个从

GuestUserPolicy
继承的
DefaultUserPolicy
类和规则
feed?
,将使用以下可能的翻译键列表:

[:"action_policy.policy.guest_user.feed?", :"action_policy.policy.default_user.feed?", :"action_policy.policy.feed?", :"action_policy.unauthorized"]

所以在你的情况下是:

en:
  action_policy:
    policy:
      investigation_review:
        new?: The investigation is in the wrong state
© www.soinside.com 2019 - 2024. All rights reserved.