Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

respond_with ArgumentError (Nil location provided. Can't build URI.):

Tags:

I have a controller that responds_with JSON for all of the RESTful actions, index, create, update etc,

class QuestionsController   respond_to :json     def index      respond_with Question.all    end  end  

However, I also have other actions in the controller. For example, in one method, it checks whether a response was correct and then tries to return a variable with a boolean true or false

respond_with correct_response  #either true or false 

However, this is giving me the error

ArgumentError (Nil location provided. Can't build URI.): 

There will also be other methods that I'll wish to respond with multiple values. In Sinatra, you can do this to respond with json

{:word => session[:word], :correct_guess => correct_guess, :incorrect_guesses => session[:incorrect_guesses], :win => win}.to_json 

How would I do that in Rails?

So, two questions, what's the proper way to write this

respond_with correct_response 

and how to respond_with multiple values in a way similar to the example I showed from a Sinatra app.

Thanks for your help.

like image 865
BrainLikeADullPencil Avatar asked Feb 03 '13 21:02

BrainLikeADullPencil


2 Answers

You want ActionController::Base#render, not respond_with. The proper way to do what you're trying to achieve here is:

render json: {word: session[:word], correct_guess: correct_guess, incorrect_guesses: session[:incorrect_guesses], win: win} 
like image 176
Chris Cashwell Avatar answered Oct 24 '22 19:10

Chris Cashwell


respond_with is actually OK for this scenario--it just happens to do some magic for you and relies on having access to info it needs; take a look at Rails 4.1.9's actionpack/lib/action_controller/metal/responder.rb.

In your case, ArgumentError (Nil location provided. Can't build URI.) is actually telling the truth--it's trying to determine a URL to use from the location header setting but isn't able to figure it out. I'd wager you could get your code working if you gave it one:

class QuestionsController   respond_to :json    def index     respond_with Question.all, location: questions_url   end end 
like image 42
turboladen Avatar answered Oct 24 '22 20:10

turboladen