Rails RecordNotFound exception occurs when there is error while fetching records from database. RecordNotFound is one of the Exception Handling class provided by Rails.
1. What is RecordNotFound Exception:
It is Exception class defined in the
errors.rb file which comes with your Rails.
2. When RecordNotFound Exception is thrown:
Code Snippet of file errors.rb mentioned above -
ActiveRecordError class is inherited from StandardError class which is subclass of Exception class. Thus ultimately Exception is superclass of StandardError class.
Sample code to reproduce the exception:
Suppose you have users table in your database, thus model User in codebase. And you try to fetch record by following code:
And your database don’t have user with id 1234352, then it will throw error as,
As mentioned in above snippet, it is thrown when ActiveRecord can not find record in the database that you are trying to fetch.
Basically, record with corresponding fields in your where clause doesn’t exist in the database.
3. Exception Handling for RecordNotFound Exception:
You can handle this exception as,
In this tutorial, we have seen what is Rails RecordNotFound exception and how to handle it in the codebase when we try to fetch records from the database.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox