Trong application_conroller.rb
thêm như sau:
# 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
Tôi thường cũng giải cứu ngoại lệ sau đây, nhưng đó là tùy thuộc vào bạn:
rescue_from ActionController::UnknownController, with: -> { render_404 }
rescue_from ActiveRecord::RecordNotFound, with: -> { render_404 }
Tạo bộ điều khiển lỗi:
class ErrorsController < ApplicationController
def error_404
render 'errors/not_found'
end
end
Sau đó, trong 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
Và điều cuối cùng là tạo ra not_found.html.haml
(hoặc bất kỳ template engine bạn sử dụng) dưới /views/errors/
:
%span 404
%br
Page Not Found
Nguồn
2014-09-15 06:34:56
này không hoạt động trong Rails 4.2.5. Tôi đoán đó là bởi vì ngoại lệ được nâng lên bởi ActionDispatch trước khi bất kỳ mã điều khiển nào được chạy. – depquid
@ depquid Tôi đã viết nó trong thời gian của Rails 4.0.x, nhưng đã thử nghiệm nó với Rails 4.2.5 - Tôi cho rằng bạn không thêm tuyến đường và không tạo ra 'errors_controller.rb' :) Nếu đó là trường hợp - hãy chắc chắn rút lại phiếu giảm giá, trừ khi bạn có nhiều lý do để hủy bỏ số này –
Rất tiếc, tôi đã không thiết lập đúng tuyến đường. Nhưng tại sao có 'rescue_from ActionController :: RoutingError, với: -> {render_404}' nếu bạn định tuyến trực tiếp đến hành động? – depquid