如何覆盖视图中的策略 class

How to override policy class in view

我正在尝试使用 Pundit gem,它可以让您像这样覆盖控制器中的策略 class

def create
  @publication = find_publication # @publication.class => Post
  authorize @publication, policy_class: PublicationPolicy
  @publication.publish!
  redirect_to @publication
end

我尝试覆盖视图中的策略 class 以及如下所示,但出现错误 unknown keyword: :policy_class

<% if policy(@publication, policy_class: PublicationPolicy).create? %>

policy 只是根据您传递给它的资源查找策略的快捷方式。

# Retrieves the policy for the given record.
#
# @see https://github.com/varvet/pundit#policies
# @param user [Object] the user that initiated the action
# @param record [Object] the object we're retrieving the policy for
# @raise [InvalidConstructorError] if the policy constructor called incorrectly
# @return [Object, nil] instance of policy class with query methods
def policy(user, record)
  policy = PolicyFinder.new(record).policy
  policy&.new(user, pundit_model(record))
rescue ArgumentError
  raise InvalidConstructorError, "Invalid #<#{policy}> constructor is called"
end

其实只是 MyPolicy.new(user, record) 的缩写。向其添加 policy_class 选项将完全没有意义。如果您已经知道自己想要什么,为什么还要动态查找?

authorize on 将在不允许的情况下引发 NotAuthorizedError 并动态找出您尝试执行的操作,因此拥有该选项是有意义的。