Order of format matters in respond_to block

Neeraj Singh

Neeraj Singh

January 25, 2010

This is a standard Rails code. I am using Rails 2.3.5 .

1class UsersController < ApplicationController
2  def index
3    @users = User.all
4    respond_to do |format|
5      format.html
6      format.js  { render :json => @users }
7    end
8  end
9end

Accidentally in one of my controllers the order of formats got reversed. The altered code looks like this.

1class UsersController < ApplicationController
2  def index
3    @users = User.all
4    respond_to do |format|
5      format.js  { render :json => @users }
6      format.html
7    end
8  end
9end

I thought order of format declaration does not matter. I was wrong.

1> curl -I http://localhost:3000/users
2HTTP/1.1 200 OK
3Connection: close
4Date: Mon, 25 Jan 2010 22:32:16 GMT
5ETag: "d751713988987e9331980363e24189ce"
6Content-Type: text/javascript; charset=utf-8
7X-Runtime: 62
8Content-Length: 2
9Cache-Control: private, max-age=0, must-revalidate

Notice the Content-Type of in the response header is <strong>text/javascript</strong> in stead of <strong>text/html</strong> .

Well I guess the order of format matters. I hope it is fixed in Rails 3.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.