0

I would like to render a default 404 page on a certain condition in my Rails 5.1 app. I have this in my controller

  def index
    ...
    if worker
    ...
    else
      puts "page not found"
      render :status => 404
    end
  end

However, even if the condition if met (my 404 branch is called), Rails is still trying to render my index.htrml.erb page, which is resulting in other errors because the expected model attributes are not there. Is there a way I can have a 404 status code returned without a page being rendered?

Dave
  • 15,639
  • 133
  • 442
  • 830

2 Answers2

1

The easiest way is:

render file: "#{Rails.root}/public/404", layout: true, status: :not_found

Another way is to raise an error which will caught as 404 by rails

Among the errors are: ActionController::RoutingError, AbstractController::ActionNotFound or ActiveRecord::RecordNotFound

Having the method not_found, it can be called when it's needed

def not_found
  raise ActionController::RoutingError.new('Not Found')
end

def index
  ...
  if worker
  ...
  else
    puts "page not found"
    not_found
  end
end

For other formats you can use just head :not_found

mmsilviu
  • 1,211
  • 15
  • 25
  • If you are using directly the first option, without being in a method or last in the method, use it like `render .... and return` – mmsilviu Apr 13 '18 at 12:53
0

The easiest way is rendering public/404 with status code 404, you have any specific layout for the 404-page layout: true otherwise layout: false. then return a false value

render :file => "#{Rails.root}/public/404", layout: false, status: 404
return false
Anand Jose
  • 638
  • 9
  • 26
  • Thx. So if I have my own 404 page defined in Apache will my throwing the 404 status from teh Rails app invoke allow my Apache 404 page to be rendered? – Dave Apr 13 '18 at 19:47
  • `render nothing: true, layout: false, status: 404` this will return 404 status to the HTTP server, in your case Apache. In production, apache will show configured 404 page. – Anand Jose Apr 15 '18 at 13:53