欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

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.

https://github.com/varvet/pundit/issues/140

返回列表