rails 使用pundit 根据参数动态验证某个action的权限
class PostsController < ApplicationController before_action :check_user def index @posts = Post.all end def new @post = Post.new end #OTHER METHODS private def check_user # params[:key] will pass the 'key' parameter # get_method(params[:action]) will return 'index?' or 'new?' # get_class(self) will return 'PostPolicy' class, you can add parameter.split('::').last if you have namespaces authorize params[:key], get_method(params[:action]), :policy_class => get_class(self) end def get_class parameter parameter.class.to_s.gsub('sController', 'Policy').constantize end def get_method parameter parameter.to_s + '?' end end
class PostPolicy < ApplicationPolicy def index? # record variable contains the key that I passed record.present? end def new? # record variable contains the key that I passed record.present? end #OTHER METHODS end
I did it this way to avoid calling authorize
to every method and be able to pass a variable from the controller to the policy for validation.