如何用Haml修改Rails公共目录错误页面?访问/404遇路由错误求解
Hey there! Let's figure out why you're hitting that Routing Error when trying to access localhost:3000/404 after setting up Haml custom error pages. Here are the most common issues and how to fix them:
By default, Rails prioritizes showing detailed debugging info over custom error pages in development. That’s why you’re seeing a Routing Error instead of your Haml page. To change this, update your config/environments/development.rb file:
# Disable detailed local error pages config.consider_all_requests_local = false # Enable exception handling to show custom error pages config.action_dispatch.show_exceptions = true
After making this change, restart your Rails server—this is crucial for the config to take effect.
Rails looks for static HTML files in the public folder by default (like public/404.html). If you’re using Haml, you have two options:
- Compile Haml to HTML manually: Convert your
404.hamlfile to404.html(use thehamlcommand line tool:haml 404.haml public/404.html) and make sure the compiled HTML file lives directly in thepublicdirectory. - Render Haml templates dynamically: If you want to avoid compiling, set up a dedicated errors controller:
- Add these routes to
config/routes.rb:get '/404', to: 'errors#not_found' get '/500', to: 'errors#internal_server_error' - Create
app/controllers/errors_controller.rb:class ErrorsController < ApplicationController def not_found render status: 404 end def internal_server_error render status: 500 end - Create Haml templates in
app/views/errors/:not_found.html.hamlandinternal_server_error.html.haml.
- Add these routes to
I know it’s obvious, but it’s easy to miss! Any changes to config files, routes, or controller setups require a server restart. Stop your current rails s process and start it again.
routes.rb Check if you have any other routes that match /404—Rails processes routes top to bottom, so if another route is catching /404 before your error page setup, it’ll trigger the Routing Error. Make sure your error page routes are placed at the bottom of routes.rb to avoid conflicts.
Give these steps a try, and you should be able to see your custom Haml error page when accessing /404!
内容的提问来源于stack exchange,提问作者Johnny Zapata

