首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pundit:未定义的方法` `authorize‘

Pundit:未定义的方法` `authorize‘
EN

Stack Overflow用户
提问于 2014-09-06 03:41:49
回答 1查看 1.5K关注 0票数 0

我正在尝试使用Pundit来验证对一些不需要数据库交互的静态视图的访问:

代码语言:javascript
复制
class StaticController < ApplicationController
    include Pundit
    authorize :splash, :home?

    def home end
end

下面是我的静态策略。home?策略总是返回true,所以我应该能够访问主视图。

代码语言:javascript
复制
class StaticPolicy < Struct.new(:user, :static)
    def initialize(user, resource)
        @user = user
        @resource = resource
    end

    def home?
        true
    end
end

相反,我得到了这样的结果:

代码语言:javascript
复制
undefined method `authorize' for StaticController:Class

如果我授权一个模型,那么Pundit就能完美地工作:

代码语言:javascript
复制
def forums_index
    @forums = Forum.all
    authorize @forums
end

但是,如果我试图在没有使用模型的操作之外使用authorize方法,我会得到:

代码语言:javascript
复制
undefined method `authorize' for StaticController:Class
EN

回答 1

Stack Overflow用户

发布于 2014-09-06 09:59:08

当你使用authorize时,你已经知道你必须自己加载和授权一些东西(如果我在这里太明显了,很抱歉)。在使用CanCan时,你必须自己加载和授权。

也就是说,考虑到您的视图没有DB交互,在我看来,对于您的情况,最好的解决方案是对您的用户进行一些自定义授权,例如

代码语言:javascript
复制
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中类似这样的东西

代码语言:javascript
复制
class UserPolicy < ApplicationPolicy
  def admin # or def home?, it's up to you
    user.admin?
  end
end

我没有测试它,但这是主要的想法,它有什么意义吗?清楚了吗?

请尝试一下,并张贴任何印象,希望它能有所帮助:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25692914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档