ActiveRecord #find_by_id with Conditions and NotFound Exception

Posted by Peter Wagenet Sat, 05 Sep 2009 20:07:00 GMT

Every so often I’ve seen code (maybe even written by yours truly) that looked something like this:

post = Post.first(:conditions => { :id => 1, :published => true })

However, this won’t raise an error like a #find(id) would. So then the following line is added:

post = Post.first(:conditions => { :id => 1, :published => true })
raise ActiveRecord::RecordNotFound unless post

But this is getting a bit messy and seems overly complicated. Fortunately, we have a better solution.

Ironically, this solution is actually well documented in the Rails docs. Any call to ActiveRecord::Base#find accepts an options hash. This means we can do things like:

post = Post.first(1, :conditions => { :published => true })

Now that looks much better.