How to show custom 404 per controller?
Is 开发者_开发百科it possible to show different error pages based on the controller?
For Rails < 3.0.
Yes, it is possible. I use this method in my application controller to render 404 message:
def render_optional_error_file(status_code)
status = interpret_status(status_code)[0,3]
if status == "404"
render :template => "/errors/404.html.erb", :status => status
else
render :template => "/errors/error.html.erb", :status => status
end
end
So, the only thing you need to do is to write this method for each controller, or you can change render
line to something like this:
render :template => error_page, :status => status
and add method:
def error_page
"/errors/404.html.erb"
end
Then you only need to write error_page
method in each controller, where you want to change default error page.
EDIT: Ups, I've just noticed that this method is deprecated in Rails 3. So there should be another way of doing it.
For Rails >=3.0:
Here is one example solution for this. Just add:
rescue_from ActionController::RoutingError, :with => :render_404
and add render_404
method:
def render_404
render :file => "errors/404.html.erb", :status => 404
end
Or if you want to add 404.html.erb
view for each controller without modifing controllers code, you can write it like this:
def render_404
render "404.html.erb", :status => 404
end
I think it should look for this error file inside current controller's view directory. I didn't check it, but I think it should work. But remember to include 404.html.erb
file in each controller's view directory. Otherwise there could be an error.
精彩评论