我正在尝试使用Pundit来验证对一些不需要数据库交互的静态视图的访问:
class StaticController < ApplicationController
include Pundit
authorize :splash, :home?
def home end
end下面是我的静态策略。home?策略总是返回true,所以我应该能够访问主视图。
class StaticPolicy < Struct.new(:user, :static)
def initialize(user, resource)
@user = user
@resource = resource
end
def home?
true
end
end相反,我得到了这样的结果:
undefined method `authorize' for StaticController:Class如果我授权一个模型,那么Pundit就能完美地工作:
def forums_index
@forums = Forum.all
authorize @forums
end但是,如果我试图在没有使用模型的操作之外使用authorize方法,我会得到:
undefined method `authorize' for StaticController:Class发布于 2014-09-06 09:59:08
当你使用authorize时,你已经知道你必须自己加载和授权一些东西(如果我在这里太明显了,很抱歉)。在使用CanCan时,你必须自己加载和授权。
也就是说,考虑到您的视图没有DB交互,在我看来,对于您的情况,最好的解决方案是对您的用户进行一些自定义授权,例如
class StaticPolicy < Struct.new(:user, :static)
def initialize(user, resource)
@user = user
@resource = resource
end
def home?
authorize @user, :admin # or suppress the second parameter and let the Policy use the 'home?' method
true
end
end在你的UserPolicy中类似这样的东西
class UserPolicy < ApplicationPolicy
def admin # or def home?, it's up to you
user.admin?
end
end我没有测试它,但这是主要的想法,它有什么意义吗?清楚了吗?
请尝试一下,并张贴任何印象,希望它能有所帮助:)
https://stackoverflow.com/questions/25692914
复制相似问题