respond_with/to rendering wrong view

Go To


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


respond_to :html, :js

def get_numbers request.format
  @numbers = Number.all
  respond_with @numbers

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.


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

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

i could render the correct view by doing:

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

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

2012-04-04 02:57
by brewster
When all you want is the js, why are you using html as well. The syntax in the respond_to block doesn't look much readable to me as well. Change it to meet your specific needs - Jatin Ganhotra 2012-04-04 05:33
im using both html and js. and not sure what you mean with the respond_to block. i removed the :only option from the example since it isn't pertinent to the problem. this is a contrived example btw - brewster 2012-04-04 06:31
Can you post the relevant routes, as well as your Gemfile.lock - moritz 2012-04-04 07:30
In your controller, you are telling it to respond with either html or js, and that will be determined when you ask for it in the Ajax request. Check your AJAX request for the format asked, and do some debugging there. Also check the relevant routes as @mosch said - Jatin Ganhotra 2012-04-04 09:12
the ajax request format is correct (text/javascript), and the route is setup properly (GET numbers#get_numbers). updated the post to show the GET request - brewster 2012-04-04 18:42


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.

2012-04-04 18:52
by Brandan
that was it! though instead of setting the default format on my route i am setting it on the url, but that was the problem nonetheless.. - brewster 2012-04-04 19:21
also... why couldn't rails match the appropriate response with just request.format - brewster 2012-04-04 19:22
I'm afraid I don't really know. It does seem strange that the logs indicate that it's responding as JS but rendering the HTML template. If you can get a minimal reproducible case, open a bug against Rails - Brandan 2012-04-04 19:35