首页 > 解决方案 > Pundit::AuthorizationNotPerformedError in PagesController#home

问题描述

我正在建立一个网站,用户可以在其中看到多首诗歌或自己写诗。我正在使用 Devise 和 Pundit 进行身份验证和授权。

当用户转到主链接(http://0.0.0.0:3000/)时,我希望他即使没有登录也能看到该页面。主页只是一个带有按钮的 HTML 页面如果单击,将重定向到所有诗歌(诗歌控制器)。

但是,我遇到以下错误:

Pundit::AuthorizationNotPerformedError in PagesController#home

application_controller.rb

class ApplicationController < ActionController::Base
  include Pundit

  protect_from_forgery with: :exception
  before_action :authenticate_user!

  after_action :verify_authorized, :except => :index, unless: :devise_controller?
  after_action :verify_policy_scoped, :only => :index, unless: :devise_controller?

  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  private

  def user_not_authorized
    flash[:alert] = "Non sei autorizzato a eseguire questa azione"
    redirect_to(root_path)
  end

end

pages_controllers.rb

class PagesController < ApplicationController
  include Pundit

  skip_before_action :authenticate_user!, only: [:home]
  # skip_after_action :verify_authorized, except: [:home]
  # after_action :verify_authorized, except: [:home]
  # before_action :authenticate_user!, except: [:home,]


  def home
  end
end

我尝试遵循本指南: Pundit::AuthorizationNotPerformedError 但我不断收到同样的错误。

我没有创建一个pages_policy.rb,但我不认为这是问题所在。

标签: ruby-on-rails

解决方案


解决了。由于PagesController是继承自ApplicationController,而后者包含before_action :authenticate_user!,我必须在 中写下以下内容PagesController

class PagesController < ApplicationController
  include Pundit
    skip_after_action :verify_authorized, only: [:home]

    skip_before_action :authenticate_user!, only: [:home]

  def home
  end
end

推荐阅读