Monday, January 26, 2009




Connect with other attendees

Thursday, January 08, 2009

Ruby tip to handle missing records

Here's quick and simple tip to cleanly handle non-existent records in Ruby.

By default if you try to use find(id) to fetch a record from your database and the id doesn't exist you'll get a RecordNotFound error like:

>> r = Record.find(9999)
ActiveRecord::RecordNotFound: Couldn't find Record with ID=9999
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:1383:in `find_one'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:1366:in `find_from_ids'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:541:in `find'
from (irb):3

You could wrap it with a begin and rescue and have the rescue clause create a new record such as:

begin
r = Record.find(id)
rescue
r = Record.new
end

Or you could simply use find_by_id which will return nil if the record is not found and re-write it as:

r = Record.find_by_id(id) || Record.new