Being a good little 404er

Before I post about how to add fragment caching I’d like to share this, in case people haven’t seen it. I remember seeing this technique in Rick Olson‘s code a while ago, so full credit to him.

ActiveRecord raises an RecordNotFound exception if it can’t find the database record with the ID you requested.

 def show   @person = Person.find(params[:id]) end 

If params[:id] doesn’t match a database record an ActiveRecord::NotFound exception will be raised. Using ActionController’s rescue_action_in_public method we can capture these exceptions and throw 404’s accordingly, and for me at least, this covers about 99% of use cases.

To do this application wide, add the following protected method to your ApplicationController.rb

 def rescue_action_in_public(e)   if e.is_a? ActiveRecord::RecordNotFound     render :file => "#{RAILS_ROOT}/public/404.html",            :status => '404 Not Found'   else     super   end end 

In reality I usually move that render call out into a render_404 method, so you can handle HTML, XML and any other types of requests. It also allows you to call it from within the controller subclasses if needed.

 def render_404   respond_to do |format|     format.html { render :file => "#{RAILS_ROOT}/public/404.html", :status => '404 Not Found' }     format.xml  { render :nothing => true, :status => '404 Not Found' }   end   true end  def rescue_action_in_public(e)   case e when ActiveRecord::RecordNotFound     render_404   else     super   end end 

To be a good little 404er with the above code all you need to do is ensure that your important database calls throw this exception, which brings me to an important point: as of Rails 1.1, the only type of find that raises a RecordNotFound exception is a find by id (read the first paragraph of documentation on the the find method). If you’re doing a different kind of find you have to handle it yourself:

 def show   @tag = Tag.find_by_name(params[:name]) or raise ActiveRecord::RecordNotFound end 

The same thing applies (i.e. raising your own exception) with find(:all) and find(:first) as well.

If you want to throw a 404 directly you can just do:

 def show   @tag = Tag.find_by_name(params[:name]) or (render_404 and return) end 

There’s discussion on the rails-core list about adding a find! method, which would make this approach even cleaner.


Category: programming Time: 2006-08-30 Views: 1

Related post

  • Being a good mentee - a protégé 2010-12-05

    The complement of the Being a good mentor question. I work with many very senior people that have vast amounts of knowledge and wisdom in Software, Engineering and our business domain. What are some tips for gaining as much knowledge from them? I don

  • How do I go from being able to write code to being a good developer? 2011-12-02

    I'm frustrated by the lack of concrete explanations on how to go from being able to script (bash, awk) and write simple applications (c, php, python) to designing and developing larger, more complicated software. It seems that on one side there are p

  • Being a good IT Manager (as opposed to a purely technical role) 2009-07-26

    Following on from this question, I'm interested how people effectively transition from being purely technical to taking on more management duties. This has been covered in great books such as Limoncelli & Hogan, so I'm interested in what the SF commu

  • Being a Good Webmaster is so hard? 2011-05-26

    How do you define a good Webmaster ? Because there are a lot of people can say "I'm a webmaster". And i say them "Yes you can use a lot tools, software etc. but this doesn't make you a Webmaster".. What is the features of a Good Webmas

  • SFTP Speed Limit (being a good neighbor on shared server) 2014-04-30

    I've been developing my website on a local server and I am ready to upload to production. The initial upload will be in the 4 GB range. I don't want to slam the server, I think a Filezilla speed limit setting will help prevent that. The default speed

  • Recover from phishing and being a good citizen 2013-10-13

    There is a mail floating around which claims that someone you know wants to share a document with you and once you follow the link in the mail you get to a site that asks your google (or others) credentials then once the unsuspecting aunt enters the

  • How to avoid programmers duplicating code 2014-04-01

    This question already has an answer here: How do I prevent unknowningly duplicating code? 6 answers While I know in a perfect world where a greenfield application was scoped out from day one with great BRD's and a competent development lead constantl

  • Unit Tests for getting the first Monday of the month 2015-04-01

    I have an application that runs hourly, and I want to use it to also send an email at the start of the day of the first Monday of the month. I searched and found information to help me code what I needed, and all my tests pass, but I want to make sur

  • use local variables outside ther functions in javascript 2016-02-11

    I've tried this: function a_function(){ var data = "information"; }); console.log(data); --------------Solutions------------- You can't. You need to create a variable outside of that scope and assign to it: var data; function a_function(){ data

  • Zend Framework: Looking Good 2006-03-06

    Like quite a few people I guess, been absorbed by looking at the first release of the new framework. Originally had been keeping notes on impressions but feel there's not much point at this time – the first release is "preview" quality and rough

  • As a non-designer what are some good sites/books/tutorials for learning web design? 2010-07-16

    My graphics skills are seriously lacking. I can see when something looks nice and when it doesn't but have a hard time coming up with anything myself given a blank slate. What should I do? --------------Solutions------------- There are a number of si

  • What are good photography projects? 2010-07-21

    I am currently in the middle of a year long photo a day project, and am beginning to think about what I will do once this is done. What types of photography projects have you done? Please keep answers to a single type. --------------Solutions--------

  • Google is good or bad for programmer? 2010-12-10

    Recently I was being interviewed by a company and faced one question. The interviewer asked me a question and at that time I didn't know the answer but if I had been asked about just 4 months ago, I could have answered it. The question was from new l

  • Learning to be a good developer: what parts can you skip over? 2011-02-01

    I have set myself the goal of becoming a decent developer by this time next year. By this I mean full experience of the development 'lifecycle,' a few good apps/sites/webapps under my belt, and most importantly being able to work at a steady pace wit

  • How likely is it for a programmer to become a good designer? 2011-05-06

    I'm a programmer, and I'm pretty good at programming. I can easily pick up most technical topics such as Linux, Systems Administration, Databases and of course, new programming languages. I even dabbled with 3d modelling and wasn't horrible at it. Ho

  • Good introduction to artificial intelligence? 2011-06-06

    I have been told that as part of my degree year I will be learning about Artificial Intelligence. My lecturers have recommended a couple of books: Artificial Intelligence: A Systems Approach (Computer Science) Artificial Intelligence (A Modern Approa

  • What are the guidelines and opinions to become a Good Programmer? 2011-06-14

    Possible Duplicate: How Can I Know Whether I Am a Good Programmer? How to learn PHP effectively? I have a doubt about myself. I think I am not good enough in programming. I was really trying very very hard to learn programming and I am dedicated to i

  • What programming languages are good for novice testers to learn? 2011-08-23

    I'm looking for a programming language to recommend to a friend considering teaching herself software testing. I have a friend who is interested in learning software testing, and I believe strongly that today's testers absolutely have to have automat

  • How to become a good team player? 2012-07-06

    I've been programming (obsessively) since I was 12. I am fairly knowledgeable across the spectrum of languages out there, from assembly, to C++, to Javascript, to Haskell, Lisp, and Qi. But all of my projects have been by myself. I got my degree in c

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.739 (s). 13 q(s)