I'd like to 'fake' a 404 page in Rails. In PHP, I would just send a header with the error code as such:
header("HTTP/1.0 404 Not Found");
How is that done with Rails?
I'd like to 'fake' a 404 page in Rails. In PHP, I would just send a header with the error code as such:
header("HTTP/1.0 404 Not Found");
How is that done with Rails?
just add this to the page you want to render to the 404 error page and you are done.
I wanted to throw a 'normal' 404 for any logged in user that isn't an admin, so I ended up writing something like this in Rails 5:
Don't render 404 yourself, there's no reason to; Rails has this functionality built in already. If you want to show a 404 page, create a
render_404
method (ornot_found
as I called it) inApplicationController
like this:Rails also handles
AbstractController::ActionNotFound
, andActiveRecord::RecordNotFound
the same way.This does two things better:
1) It uses Rails' built in
rescue_from
handler to render the 404 page, and 2) it interrupts the execution of your code, letting you do nice things like:without having to write ugly conditional statements.
As a bonus, it's also super easy to handle in tests. For example, in an rspec integration test:
And minitest:
OR refer more info from Rails render 404 not found from a controller action
HTTP 404 Status
To return a 404 header, just use the
:status
option for the render method.If you want to render the standard 404 page you can extract the feature in a method.
and call it in your action
If you want the action to render the error page and stop, simply use a return statement.
ActiveRecord and HTTP 404
Also remember that Rails rescues some ActiveRecord errors, such as the
ActiveRecord::RecordNotFound
displaying the 404 error page.It means you don't need to rescue this action yourself
User.find
raises anActiveRecord::RecordNotFound
when the user doesn't exist. This is a very powerful feature. Look at the following codeYou can simplify it by delegating to Rails the check. Simply use the bang version.
To test the error handling, you can do something like this: