行家
policy doc
说它调用了
current_user
方法检索发送到的第一个参数中的内容
initialize
current_admin_user
,则必须在
ApplicationController
类似这样的类:
Ref
class ApplicationController < ActionController::Base
// ...
def pundit_user
current_admin_user // or whatever based on ActiveAdmin initializer config
end
end
为了使定义的策略工作,您必须调用
authorize
控制器内的操作与相应策略模型的实例。所以如果你有一个
PostPolicy
你想授权
update
行动,您必须执行以下操作:
controller do
def update
@post = Post.find(params[:id])
authorize @post // the current user will be automatically sent to the PostPolicy
super
end
end
批准
方法自动推断
Post
将有一个匹配的
后政策
类,并实例化该类,交给当前用户和给定的记录。然后从动作名称推断,它应该调用
update?
关于这项政策。在这种情况下,你可以想象
批准
会这样做:
unless PostPolicy.new(current_user, @post).update?
raise Pundit::NotAuthorizedError, "not allowed to update? this #{@post.inspect}"
end
AdminUserPolicy
就像你已经做的那样。然后在
index
您的行动
AdminUserController
controller do
def index
@users = AdminUser.all
authorize @users // NOT `authorize current_admin_user`
super
end
end
您可以将第二个参数传递给
批准
如果要检查的权限名称与操作名称不匹配。例如:
def publish
@post = Post.find(params[:id])
authorize @post, :update?
@post.publish!
redirect_to @post
end