4

我是 ruby​​ 的初学者,找不到如何在 Rails 5 中创建自定义 404-401 页面的解决方案。有什么建议吗?我用“page_404”操作创建了一个控制器“ErrorPages”。请帮帮我。

4

1 回答 1

4

尝试这个:

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

路线.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
于 2017-03-17T10:20:58.600 回答