Thursday, January 17, 2008

ActiveRecord : Find vs Find_By_Id

Here's a silly mistake I make, perhaps others make it as well.  You've got an id (primary key) for one of your objects, so you do this:

obj = Object.find(id)

and off you go.  Right? 

Small problem that you might not even realize.  If there's no record in your database with that id, then what do you get, a nil pointer?  Nope - you get an Exception thrown!  I kick myself every time I do that and make the wrong assumption.

If you want a nil pointer returns, do an Object.find_by_id(id) instead.  This will return nil if the object is not found.


Anybody got the background on why that is?


Technorati tags: , ,


j said...

.find id assumes you know there's an object with that id - hence the exception when it's not there.

.find_by_id id is like any other search - find it if it's there, return nil if not.

Ben said...

Thanks a lot for this - I was just about to make the same mistake. Just the pithy summary I needed.

Anonymous said...

Yes, I've found this as well, and believe it's poor API design.

.find should be re-worked to be similar to .save! and .save.