if someone messes with the :id on a url, for example /edit/15 and id 15 does not exist, how can I display my own “page does not exist” error page instead of processing the view (which would throw an error since it’s expecting data)
I know how to add code to check that method-by-method, but is there some global way to trap all such errors within a controller regardless of the method?
I’d like to avoid having to copy/paste something like
redirect_to "/invalid_page.html" and return if @something.nil?
in each and every method where I do
@something = MyModel.find(params[:id])
Of course if it’s a totally bogus url, such as myapp.com/nosuchpage, then the /public/404.html page gets shown. But if it’s a valid route, but an invalid ID, it throws an exception down in the view where the view is unexpectedly dealing with nil data and I have no idea if there’s a controller-wide place to trap and handle that exception.
take a look at
rescue_fromin the rails api docs. if you usefindto load your ActiveRecord instances, it will throw anActiveRecord::RecordNotFoundexception if there is no record with the given id. you can tell your controller to rescue this exception and call a method/action instead, like this:if you’re on Mongoid you’ll have to use
Mongoid::Errors::DocumentNotFound. if you use a custom finder, make sure it raises the appropriate exception.