Search code examples
jsonruby-on-rails-3routesrespond-with

respond_with redirecting when format=json


I'm encountering a strange behavior in my controllers. They seem to occasionally want to redirect instead of render a json response.

respond_to :json, :html, :js

def create
  @favorite = current_user.favorites.build(:location_id=>params[:location_id])
  if @favorite.save
    respond_with(@favorite)
  else
    respond_with(@favorite.errors)
  end
end

I think it works most of the time but today I was notified of this error:

NoMethodError: undefined method `favorite_url' for #<FavoritesController:0x00000006171dc0>

The params hash was logged as:

{"format"=>"json",
 "action"=>"create",
 "user_id"=>"56",
 "auth_token"=>"iGSty8CMIaWsbShYZEtw",
 "location_id"=>"47943",
 "controller"=>"favorites"}

Especially strange since it seems to work most of the time... I have changed a few of my other controllers to use the old format.json { render :json => @object } syntax but I'd like to avoid that if possible.

How could this be?


Solution

  • On paths that are not GETs, respond_with tries to redirect to the url for whatever it is given. You can override this with a custom Responder