snippetrubyrailsCritical
How to redirect to a 404 in Rails?
Viewed 0 times
railsredirect404how
Problem
I'd like to 'fake' a 404 page in Rails. In PHP, I would just send a header with the error code as such:
How is that done with Rails?
header("HTTP/1.0 404 Not Found");How is that done with Rails?
Solution
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
Rails also handles
This does two things better:
1) It uses Rails' built in
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
render_404 method (or not_found as I called it) in ApplicationController like this: def not_found
raise ActionController::RoutingError.new('Not Found')
endRails also handles
AbstractController::ActionNotFound, and ActiveRecord::RecordNotFound the same way.This does two things better:
1) It uses Rails' built in
rescue_from handler to render the 404 page, and2) it interrupts the execution of your code, letting you do nice things like:
user = User.find_by_email(params[:email]) or not_found
user.do_something!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:
# RSpec 1
lambda {
visit '/something/you/want/to/404'
}.should raise_error(ActionController::RoutingError)
# RSpec 2+
expect {
get '/something/you/want/to/404'
}.to raise_error(ActionController::RoutingError)And minitest:
assert_raises(ActionController::RoutingError) do
get '/something/you/want/to/404'
endOR refer more info from Rails render 404 not found from a controller action
Code Snippets
def not_found
raise ActionController::RoutingError.new('Not Found')
enduser = User.find_by_email(params[:email]) or not_found
user.do_something!# RSpec 1
lambda {
visit '/something/you/want/to/404'
}.should raise_error(ActionController::RoutingError)
# RSpec 2+
expect {
get '/something/you/want/to/404'
}.to raise_error(ActionController::RoutingError)assert_raises(ActionController::RoutingError) do
get '/something/you/want/to/404'
endContext
Stack Overflow Q#2385799, score: 1101
Revisions (0)
No revisions yet.