# Handling ActiveRecord::RecordNotFound errors

**URL:** <https://www.ruby-forum.com/t/handling-activerecord-recordnotfound-errors/145522>\
**Category:** Rails\
**Created:** [August 11, 2008, 7:49am UTC](https://www.ruby-forum.com/t/handling-activerecord-recordnotfound-errors/145522 "2008-08-11T07:49:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![asoto](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/58956e/32.png) [@asoto](https://www.ruby-forum.com/u/asoto)\
**Post date:** [August 11, 2008, 7:49am UTC](https://www.ruby-forum.com/t/handling-activerecord-recordnotfound-errors/145522/1 "2008-08-11T07:49:14Z")

</div>

Can anyone explain why an ActiveRecord::RecordNotFound error is only  
thrown on a regular id-based find, such as Product.find(123)? For  
example, if you’re using a dynamically generated attribute find method,  
such as Product.find\_by\_name(‘asdfd’), and no results match, it just  
returns nil, and no error is thrown.

Are you guys handling this in your controllers or models, and how are  
you handling it (i.e. redirecting, manually raising an error, etc)?

---

<div class="post-metadata">

**Author:** ![asoto](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/58956e/32.png) [@asoto](https://www.ruby-forum.com/u/asoto)\
**Post date:** [August 11, 2008, 10:08am UTC](https://www.ruby-forum.com/t/handling-activerecord-recordnotfound-errors/145522/2 "2008-08-11T10:08:03Z")

</div>

On Aug 11, 6:49 am, Alex S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> Can anyone explain why an ActiveRecord::RecordNotFound error is only  
> thrown on a regular id-based find, such as Product.find(123)? For  
> example, if you’re using a dynamically generated attribute find method,  
> such as Product.find\_by\_name(‘asdfd’), and no results match, it just  
> returns nil, and no error is thrown.

That’s expected. The reasoning being that if you look up a record by  
id then you’re expecting the record to be there, so if it’s missing  
that’s an exceptional condition.  
On the other hand, with a find :first (which is what find\_by\_xxx ends  
up doing) or find :all, you don’t have that expectation. For example  
the user has decided to search for records matching a set of criteria  
or something along those lines and so there not being any records to  
return is a perfectly normal thing.  
How you handle this is completely application dependant (it might be  
as simple as rendering ‘No results found’)

Fred
