Pundit Gem Index Page阻止访问

时间:2016-11-10 19:59:16

标签: ruby-on-rails ruby pundit

我正在使用pundit gem并试图弄清楚如何使用它来阻止访问属于current_user以外的用户的索引页。

这些示例仅讨论如何将结果范围限定为current_user,但如果current_user不是记录的所有者,则不会如何实际阻止对页面本身的访问。

任何帮助表示赞赏

由于

1 个答案:

答案 0 :(得分:1)

也许你想要这样的东西? (对于类ModelName)

# /policies/model_name_policy.rb

class ModelNamePolicy
  attr_reader :current_user, :resource

  def initialize(current_user, resource)
    @current_user = current_user
    @resource = resource
  end

  def index?
    current_user.authorized_to_edit?(resource)
  end

end

# /models/user.rb

class User < ActiveRecord::Base

  def authorized_to_edit?(resource)
    admin? | (id == resource.created_by) # Or whatever method you want to call on your model to determine ownership
  end

end

编辑:请注意,您还需要从控制器调用authorize来调用策略。