I noticed some strange behaviour while testing out a couple of things
regarding building an API. Suppose I have a very basic Rails app with
just one resource “widgets”, I’d have the following URLs:
First URL shows the widgets index using HTML, the second one using
XML. If however, instead of requesting “widgets.xml”, I’m requesting
just the first URL but with setting the HTTP Accept header to “Accept:
application/xml” I would expect to get results using my XML builder.
However, it returns HTML content (and sets Content-Type to “text/
Now, this is clearly different behaviour for what would be identical
requests. However, if I include a respond_to block in my controller:
respond_to do |format|
It works just as expected: setting the Accept header does in fact
influence what is returned (XML or HTML). However, this means I have
to include a respond_to block in every controller method, which I
think is undesirable.
So in conclusion, format switching works without respond_to block, but
only if you specify an extension in the URL, not if you use the
“Accept:” header. If you include a respond_to block, then format
switching works also by using the “Accept:” header.
Can someone explain if (and why) this behaviour is correct? Using