6

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?

Dan Hixon
  • 825
  • 11
  • 17

1 Answers1

3

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

John
  • 549
  • 1
  • 5
  • 15
  • 1
    Thanks! I just spend an hour researching custom responders (https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/responder.rb) - It seems that my particularr problem was that I have a nested route and wasn't providing the parent resource. I think all I need to do is respond with this: `respond_with(current_user, @favorite)` – Dan Hixon May 10 '11 at 15:12