解决方法
在application_conroller.rb中添加以下内容:
# You want to get exceptions in development,but not in production. unless Rails.application.config.consider_all_requests_local rescue_from ActionController::RoutingError,with: -> { render_404 } end def render_404 respond_to do |format| format.html { render template: 'errors/not_found',status: 404 } format.all { render nothing: true,status: 404 } end end
我通常也拯救以下例外,但这取决于你:
rescue_from ActionController::UnknownController,with: -> { render_404 } rescue_from ActiveRecord::RecordNotFound,with: -> { render_404 }
创建错误控制器:
class ErrorsController < ApplicationController def error_404 render 'errors/not_found' end end
然后在routes.rb
unless Rails.application.config.consider_all_requests_local # having created corresponding controller and action get '*path',to: 'errors#error_404',via: :all end
最后一点是在/ views / errors /下创建not_found.html.haml(或者你使用的任何模板引擎):
%span 404 %br Page Not Found