ruby-on-rails-3respond-with

respond_with/to rendering wrong view


I'm trying to understand why respond_with/to is rendering the wrong view...

controller

respond_to :html, :js

def get_numbers
  Rails.logger.info request.format
  @numbers = Number.all
  respond_with @numbers
end

when making an ajax request, the rails log shows the format is JS, and the request format is text/javascript, but it renders the html view.

log

Started GET "/numbers/get_numbers?_=1333564838110" for 127.0.0.1 at 2012-04-04 11:40:38 -0700
Processing by NumbersController#get_numbers as JS
  ...
text/javascript
  Rendered numbers/get_numbers.html.haml within layouts/application (106.4ms)

and i have both a get_numbers.html.haml & get_numbers.js.coffee view in views/numbers

i could render the correct view by doing:

respond_with @numbers do |format|
  format.js {}
end

but shouldn't it be rendering the js view with just respond_with @numbers


Solution

  • If you want the response to be JavaScript when no format is explicitly specified (meaning no .html or .js in the URL), you can set the default format parameter in your route:

    match '/numbers/get_numbers(.:format)' => 'numbers#get_numbers', :defaults => { :format => :js }
    

    You might also get your desired results by switching the order of the formats in your call to respond_to, since it seems to default to the first one, but I haven't tested that.