Find or 404

There’s a pattern I use often: find a record or throw a 404. In my Rails apps that means literally throwing a 404 exception. After hard-coding that logic in my controllers countless times, I’ve decided to abstract it out and this is how it works. Instead of:


you now do


It also works for associations:

blog = Blog.fof.find(blog_id)
post = blog.posts.fof.find(id)

Fof stands for “Find or Four oh four”. The code to accomplish that is:

class NotFound  e
    if arguments.last.is_a? Hash
      arguments = arguments[0..-2].inspect[1..-2] + ", " + arguments.last.inspect[1..-2]
      arguments = arguments.inspect[1..-2]
    raise"Not found: #{}.#{method}(#{arguments}): #{e.message}")

class ActiveRecord::Base
  def self.fof
    @_fof ||=

Now that I think about it, I could have called it fofof.

Update: this is now a gem.

Update: this is actually useless.

3 thoughts on “Find or 404

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.