簡體   English   中英

Rails 正在路由到找不到頁面而不是 404 錯誤

[英]Rails is routing to Page not found instead of 404 error

我最近創建了一個errors_controller.rb文件,它基本上會將所有不存在的頁面甚至那些非管理員用戶未授權的頁面路由到 404 頁面:

class ErrorsController < ApplicationController
    def page_not_found
      show_404
    end
  end

然后在我的routes.rb文件中:

match '*path', via: :all, to: 'errors#page_not_found'

我正在使用Pundit gem 進行授權,這是我的用戶政策:

class UserPolicy < ApplicationPolicy
    class Scope < Scope
      def resolve
        scope.all
      end
    end

    def index?
      user.admin? 
    end 
  end

現在的問題是,每當我訪問一個不存在的頁面時,它都會向我顯示:

在此處輸入圖像描述

但是,如果非管理員用戶訪問未經授權訪問的頁面(例如 localhost:3000/users-list),則會顯示以下內容:

在此處輸入圖像描述

每當未經授權的用戶訪問只能由管理員訪問的頁面時,如何確保在我的公共文件夾中顯示 404 頁面或特定頁面? 更新:這是我的application_controller.rb文件的內容:

class ApplicationController < ActionController::Base
    include Pundit
    protect_from_forgery with: :exception
    before_action :configure_permitted_parameters, if: :devise_controller?
    rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
    rescue_from ActiveRecord::RecordNotFound, with: :show_404

    def after_sign_in_path_for(resource)
       stored_location_for(resource) || contacts_path
    end

    def after_sign_up_path_for(resource)
       after_sign_in_path_for(resource)
    end

     protected

          def configure_permitted_parameters
               devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:user_avatar, :name, :email, :password, :password_confirmation)}

               devise_parameter_sanitizer.permit(:account_update) { |u| u.permit(:user_avatar, :name, :email, :password, :current_password)}
          end

    private

    def user_not_authorized
      flash[:danger] = "You are not authorized to perform this action."
      redirect_to action: :index
    end 

    def show_404
      render template: "errors/404", status: 404
    end 
end

您應該在 controller 上重寫user_not_authorized ,當非管理員用戶訪問未經授權訪問的頁面時調用

def user_not_authorized
  show_404
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM