Forum: Ruby on Rails Behaviour Accept header vs. respond_to

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4e112f2d96bff9ae3bded5276a13d2d7?d=identicon&s=25 tieleman (Guest)
on 2008-10-16 13:30
(Received via mailing list)
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
8217faf2bfdfa7daf10135d41ddd421e?d=identicon&s=25 Jeff Cohen (jeff)
on 2008-10-16 17:12
(Received via mailing list)
On Oct 16, 6:26 am, tieleman <tiele...@gmail.com> wrote:
> just the first URL but with setting the HTTP Accept header to "Accept:
> end
>
> 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
This topic is locked and can not be replied to.