【问题标题】:how to use namespace in gem Pundit如何在 gem Pundit 中使用命名空间
【发布时间】:2016-05-25 08:35:01
【问题描述】:

我有 2 个控制器,1 个用于用户,1 个用于管理员。

控制器/articles_controller.rb

class ArticlesController < ActionController::Base
  ...
  def show 
    @article = Article.find(parmas[:id])
    authorize @article
  end
  ...
end

controllers/admin/articles_controller.rb

class Admin::ArticlesController < AdminController
  ...
  def show 
    @article = Article.find(parmas[:id])
    authorize @article
  end
  ...
end

我有 2 个文件策略 政策/article_policy.rb

class ArticlePolicy
  extend ActiveSupport::Autoload
  autoload :Admin

  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

  def show?
    # allow show for every user. 
    true 
  end  
end

还有一个文件policy/admin/article_policy.rb

class Admin::ArticlePolicy

  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

  def show?
    # only show if use have role manager 
    user.manager? 
  end  
end

但是当我使用帐户用户在 /admin/articles/1/ 显示文章时。它显示正常,应该是“拒绝访问”。

如何解决这个问题? (我使用 gem pundit 1.10)。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 pundit


    【解决方案1】:

    使用授权方法将命名空间作为参数传递。

    class ArticlesController < ActionController::Base
      ...
      def show 
        @article = Article.find(parmas[:id])
        authorize [:admin, @article]
      end
      ...
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 2016-01-05
      相关资源
      最近更新 更多