The maze book for programmers!

Algorithms, circle mazes, hex grids, masking, weaving, braiding, 3D and 4D grids, spheres, and more!

DRM-Free Ebook

The Buckblog

assorted ramblings by Jamis Buck

Rendering empty responses

5 March 2007 — 1-minute read

Sometimes (and especially once you start dealing with writing web services) you’ll find yourself wanting to return an empty response, with only a status code and (possibly) a few headers set.

You can do this easily enough using the render method:

headers['Location'] = person_url(@person)
render :nothing => true, :status => "201 Created"

That, however, is unbearably verbose, especially when you find yourself needing to do it in multiple places.

Enter the head method:

head :created, :location => person_url(@person)

There, isn’t that beautiful?

Reader Comments

oooh, nice. Handy for things like mod_xsendfile1, too.


There, isn’t that beautiful?

Yes. Yes, it sure is :-)

Very nice, but…. Are the symbols for the status codes listed anywhere? I found a ticket discussing them: but not any indication anywhere I could think to look for what the authoritative list of symbols is.

I guess it looks like it’s these just underscored and lowercased, right?

Only in ruby can we claim that two lines are unbearably verbose :)

Tim, the list of codes that Rails understands is in action_controller/status_codes.rb. It’s just those codes underscored and lowercased, as you said.

Also, you can use those same codes in tests, in assert_response. So you can say “assert_response :created”, etc. Probably only in edge rails, though.

Beautiful indeed.

The HTTP status code symbols work for assert_response in 1.2.1 as well.

I’ve noticed that using the head method still sets the Content-Type header to ‘text/html’. Is there anyway to override this default without specifying :content_type to head every time?

The list of codes Jamis linked to is useful, but a nice companion can be found on the W3C site1.


An OT question, but why do you return 201 instead of 202 (Accepted). I assume you’re talking about one-way SOAP messages.

More out of curiosity than anything else.

cheers, dim

Dmitri, primarily because we’ve opted to follow how the atompub spec does this, and it requires that “201 Created” be used to indicate that a new resource has been created.