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?
ActiveRecord::RecordNotFound: Couldn’t find User with ID=45
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.
2 Replies to “Record not found – A simple way to handle…”
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.
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. 🙂