Rails - Pundit,如何只为未登录的用户显示控制器索引

Rails - Pundit, how to show controller index only for not logged in users

我正在使用 Pundit 进行授权,我是新手,之前只使用过 Cancan 和 Cancancan。

我有一个没有模型的索引页。此页面应该只对未登录的用户可见(仅限访客)。

我似乎只能让页面显示给所有人或没有人。

application_policy.rb

class ApplicationPolicy
  attr_reader :user, :record

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

  def index?
    false
  end

  def show?
    false
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  class Scope
    attr_reader :user, :scope

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

    def resolve
      scope.all
    end
  end
end

splash_controller.rb

class SplashController < ApplicationController

  def index
    authorize :splash, :index?
  end

end

splash_policy.rb

class SplashPolicy < ApplicationPolicy

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

  def index?
    not user?
  end

end

我已经注释掉了一个新的初始化方法,因为我假设我需要重写它,但我不太确定语法。

我猜专家在这里的做法有点错误,因为它是为授权用户执行某些操作而构建的,而不是定义您在未登录时看到的内容。

这通常是我会用控制器逻辑解决的问题,当他们在 before_action 中登录时,可能会将所有用户重定向到其他路径。

虽然在无头策略中使用此方法,但您仍然可以在 pundit 中执行此操作( https://github.com/varvet/pundit/blob/master/README.md#headless-policies).

 def index?
    user.blank?
 end