Rendering empty responses
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:
1 2 |
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:
1 |
head :created, :location => person_url(@person) |
There, isn’t that beautiful?
Reader Comments
oooh, nice. Handy for things like mod_xsendfile1, too.
[1] http://celebnamer.celebworld.ws/stuff/mod_xsendfile/
5 Mar 2007
Yes. Yes, it sure is :-)
5 Mar 2007
Very nice, but…. Are the symbols for the status codes listed anywhere? I found a ticket discussing them: http://dev.rubyonrails.org/ticket/2649 but not any indication anywhere I could think to look for what the authoritative list of symbols is.
5 Mar 2007
I guess it looks like it’s these just underscored and lowercased, right?
http://www.iana.org/assignments/http-status-codes
5 Mar 2007
Only in ruby can we claim that two lines are unbearably verbose :)
5 Mar 2007
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.
5 Mar 2007
Beautiful indeed.
5 Mar 2007
The HTTP status code symbols work for assert_response in 1.2.1 as well.
7 Mar 2007
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?
7 Mar 2007
The list of codes Jamis linked to is useful, but a nice companion can be found on the W3C site1.
1 http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
7 Mar 2007
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
21 Mar 2007
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.
21 Mar 2007