Behaviour Accept header vs. respond_to

Hi list,

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:

http://somehost/widgets http://somehost/widgets.xml

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/ html").

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|   format.html   format.xml end

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 Rails 2.1.1.

Kind regards,

Sjoerd Tieleman

I believe it's because in the first case, /widgets.xml, your routes.rb is helping to determine the :format for you (assuming you've still got the default routes in your routes.rb).

Rails won't look at the Accept header automatically - you have to use a respond_to block to do that. As for why that is, I'm not sure - I agree it might be nice for Rails to set the :format based on the Accept header as well as by route pattern.

Jeff

purpleworkshops.com softiesonrails.com