Dave
Dave

Reputation: 19170

How do I render a 404 without actually rendering my web page?

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?

Upvotes: 0

Views: 726

Answers (2)

Anand Jose
Anand Jose

Reputation: 658

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

Upvotes: 0

mmsilviu
mmsilviu

Reputation: 1451

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

Upvotes: 1

Related Questions