Record not found – A simple way to handle it.


39 sec read

Here is a simple tip to handle Record not found exception.
I found many programmers uses code like if User.find(33) then do something. If the id is not present then Active Record throws Record not found Exception which can be caught and handled using begin-rescue. But the simple way is?

[source language=html]
ActiveRecord::RecordNotFound: Couldn’t find User with ID=45
from /Programs/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/
lib/active_record/base.rb:1586:in `find_one’
from /Programs/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/
lib/active_record/base.rb:1569:in `find_from_ids’
from /Programs/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/
lib/active_record/base.rb:616:in `find’
from (irb):1
A better approach would be to check whether record exists in database find_by_id helper and/or exists?
User.find_by_id(id) returns the record if found or else returns nil.
User.exists?(id) returns true if the record is found else returns false.
Hope you will like this simple tip, if you know some other right and short way, please post it as a comment.

Related posts:

2 Replies to “Record not found – A simple way to handle…”

  1. Just a small note, its generally recommended to use the dynamic finders instead of .exists?. As exists? method would fire a query to check for the existence of the record in the database.

  2. You may also notice, in Rails 3.1.3 at least, that if you leave of the desc or the desc is .blank? then rake -T will not show that task. You may have ntcioed that a few tasks that used to be visible in rake -T prior to Rails 3, no longer show up. That’s because the rails team decided to trim the list of tasks displayed and, for example in databases.rake, you will find that the desc for those tasks is commented out. Now you know another reason rake -T may not show rake tasks. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *