Tuesday, July 28, 2009

Avoid ActiveRecord::RecordNotFound Errors

When querying a database for specific model IDs, Active Record normally returns an "ActiveRecord::RecordNotFound" error if the model ID you are searching for does not exist. For instance, if you run the following command:


Post.find(1)


and record #1 does not exist, you will get the Active Record error. In some cases, however, it's actually desirable for Active Record to return nil for the result instead of producing this error. In these cases, use the 'find_by_id' method instead of the 'find' method. For instance, you could run this command instead:


Post.find_by_id(1)


and you will simply get back an empty set. This method can also be used inside of the 'will_paginate' helpers like so:


Post.paginate_by_id(1)


and again you will end up with an empty page with zero results instead of the normal Active Record error.

No comments: