Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: How do I change the behavior of RecordNotFound?

When going to on object's show page with an id that doesn't exist, the RecordNotFonud exception is thown. Is there a way I can redirect to some error page, or maybe a different action when this error is thrown?

like image 384
NullVoxPopuli Avatar asked Dec 12 '22 09:12

NullVoxPopuli


2 Answers

You may use rescue_from if you are using Rails 3:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :render_404

  def render_404
    respond_to do |format|
      format.html { render :action => "errors/404.html.erb", :status => 404 }
      # and so on..
    end
  end
end

Yes, you can also do a redirect instead of render, but this is not a good idea. Any semi-automatic interaction with your site will think that the transfer was successfull (because the returned code was not 404), but the received resource was not the one your client wanted.

like image 70
Arsen7 Avatar answered Mar 08 '23 15:03

Arsen7


In development mode you'll see the exception details but it should automatically render the 404.html file from your public directory when your app is running in production mode.

like image 35
James Avatar answered Mar 08 '23 14:03

James