Nel application_conroller.rb
aggiungere la seguente:
# 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
Io di solito anche Salvataggio seguenti eccezioni, ma che sta a voi:
rescue_from ActionController::UnknownController, with: -> { render_404 }
rescue_from ActiveRecord::RecordNotFound, with: -> { render_404 }
Creare il controller errori:
class ErrorsController < ApplicationController
def error_404
render 'errors/not_found'
end
end
Poi in 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
E l'ultima cosa è quello di creare not_found.html.haml
(o qualsiasi motore di template si usa) sotto /views/errors/
:
%span 404
%br
Page Not Found
fonte
2014-09-15 06:34:56
Questo non funziona in Rails 4.2.5. Sto indovinando che è perché l'eccezione è sollevata da ActionDispatch prima che venga eseguito qualsiasi codice del controller. – depquid
@depquid L'ho scritto ai tempi di Rails 4.0.x, ma l'ho appena testato con Rails 4.2.5 - Suppongo che tu non abbia aggiunto route e non abbia creato il file 'errors_controller.rb' :) Se questo è il caso - assicurati di ritirare il downvote, a meno che tu non abbia più motivi per lasciarlo. –
Spiacente, non ho impostato correttamente il percorso. Ma perché, 'rescue_from ActionController :: RoutingError, con: -> {render_404}' se stai indirizzando direttamente all'azione? – depquid