Rendering empty responses

Posted by Jamis on March 05, 2007 @ 11:41 AM

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?

Posted in Tips & Tricks

Comments

Have something to add? Click here to leave a comment.

05 Mar 2007

1. dm said...

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

[1] http://celebnamer.celebworld.ws/stuff/mod_xsendfile/

2. Danger said...

There, isn’t that beautiful?

Yes. Yes, it sure is :-)

3. Tim Connor said...

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.

4. Tim Connor said...

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

http://www.iana.org/assignments/http-status-codes

5. Adam Sanderson said...

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

6. Jamis said...

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.

7. Chris said...

Beautiful indeed.

07 Mar 2007

8. John Bledsoe said...

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

9. John Bledsoe said...

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?

10. Jim Kane said...

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

21 Mar 2007

11. Dmitri Colebatch said...

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

12. Jamis said...

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.