如何在登录后使用 Pundit 使 Active Admin 正常工作

7
我已经在我的应用程序中添加了配置pundit适配器授权。
config.authorization_adapter = ActiveAdmin::PunditAdapter

当我使用admin@example.com的凭据登录时,我遇到了这个错误。
Pundit::NotDefinedError in Admin::Dashboard#index
unable to find policy AdminUserPolicy

Extracted source (around line #2):

insert_tag active_admin_application.view_factory["page"]

我创建了这些文件在我的policies/active_admin文件夹中。
adminuser_policy.rb
module ActiveAdmin
class AdminUserPolicy < ApplicationPolicy
class Scope < Struct.new(:user, :scope)
  def resolve
    scope
  end
end
def home?
true
end

def index?
true 
end
def show?
true 
end
def new?
true
end

def create?
 true
end

def update?
true 
end

  def destroy?
    true 
 end
end

end

page_policy.rb

module ActiveAdmin
class PagePolicy < ApplicationPolicy
  class Scope < Struct.new(:user, :scope)
  def resolve
    scope
  end
 end
   def index?
      true
   end

   def show?
     true
   end
  end
end

我缺少什么?谢谢你的帮助!
2个回答

5
我找到了答案!
在 active admin 初始化文件中添加以下两行代码:
config.authorization_adapter = ActiveAdmin::PunditAdapter 

#this line sets the default policy to application_policy.rb
config.pundit_default_policy = "ApplicationPolicy"

我需要在app/admin/dashboard.rb下添加这段代码。

def index
  authorize :dashboards, :index?
end

然后,我在我的策略文件夹中创建了一个名为dashboard_policy.rb的文件,并添加了以下代码。
class DashboardPolicy < ApplicationPolicy
   def dashboard?
   true
  end
  def index?
   true
  end
 end

那样就能运行了!

是的,你上面粘贴的代码有问题。请具体说明你的app/admin/dashboard.rb文件的全部内容。 - Jesse Sanford

1
我所要做的就是遵循文档

config/initializers/active_admin.rb

ActiveAdmin.setup do |config|
  # ...
  config.authorization_adapter = ActiveAdmin::PunditAdapter
  # ...
end

app/policies/active_admin/page_policy.rb(注意active_admin文件夹!)

module ActiveAdmin
  class PagePolicy < ApplicationPolicy
    def show?
      case record.name
      when 'Dashboard'
        true
      else
        false
      end
    end
  end
end

我喜欢这个答案,它的代码和配置比被接受的答案少。更符合“约定优于配置”的理念。 - senya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接