respond_to with .text versus .txt

Posted by Luke Francl
on Saturday, September 22

Public service message:

If you’re using ActionController’s respond_to to render a text view of your data, you do it with .text like this:

1
2
3
4
5
6
7
8
9
10
def index
  @foos = Foo.find(:all)

  respond_to do |format|
    format.html
    format.text do
      render :text => @foos.map(&:some_method).join(" ")
    end
  end
end

But the extension you have to use to access the text format depends on your version of Rails.

Rails 1.2.3

In Rails 1.2.3, you must access the text format with the .txt extension because in Rails 1.2.3 only .txt is mapped as an extension for the text/plain MIME type (see mime_type.rb). If you use a .text extension, the browser will return a HTTP 406 error code and nothing will render.

Rails 2.0/Edge Rails

However, it looks like in Rails 2.0, the behavior has been changed and both .text and .txt extensions will work because a facility for extension synonyms has been added (see mime_type.rb and mime_types.rb).

Hopefully teh googles will index this and save somebody else the time it took me to figure out why mine respond_to block wasn’t working!