ruby-on-railshttp-status-code-404custom-pages

Custom 404 page rails


I am beginner in ruby and cant find solution how to create custom 404-401 page in Rails 5. Any suggestion? I've created a controller "ErrorPages" with action "page_404". Help me please.


Solution

  • Try this:

    class ApplicationController < ActionController::Base
      rescue_from ActiveRecord::RecordNotFound, with: :on_record_not_found
      rescue_from AbstractController::ActionNotFound, with: :on_record_not_found
      rescue_from ActionController::RoutingError, with: :on_routing_error
      rescue_from CanCan::AccessDenied, with: :on_access_denied
    
      def render_404
        if params[:format].present? && params[:format] != 'html'
          head status: 404
        else
          render 'application/404', status: 404
        end
      end
    
      def on_access_denied
        if params[:format].present? && params[:format] != 'html'
          head status: 401
        else
          render 'application/401', status: 401
        end
      end
    
      def on_record_not_found
        render_404
      end
    
      def on_routing_error
        render_404
      end
    end
    

    routes.rb

    Rails.application.routes.draw do
      get '*unmatched_route', :to => 'application#render_404'
    end
    

    /app/views/application/404.html.slim

    .content
     .row
      .col-md-12
        h1 404