Rails response_with does not display the status of the rest of the call

I am trying to make a simple rest api with rails using the response_with method, but it does not want to output any status messages like

for example, I want it to not only return json to call get, but also ok. Same thing when a message or delete works / does not work.

Several textbooks suggest using additional state parameters, but they do not seem to affect the output at all.

def index @conns = Connection.all respond_with(@conns, :status => :ok) end 

This returns the same thing as if: status =>: ok was not.

Any ideas?

Thanks!

+4
source share
2 answers

This is because it will implicitly return :status => :ok when the answer is ok, and I think it is :)

Try using a different status code, for example

 :status => :not_found 

There is a complete list of status codes in the official ruby ​​on the guide rails.

+2
source

:status => :ok sets the status code of the HTTP header, i.e. same as :status => 200 . If you want to add something to the response body, you will need to add it explicitly, for example.

respond_with({:conns => @conns, :status => :success}.to_json)

EDIT

OK, so this will not work. If you don't need to respond to anything other than JSON, you can just use the good old render :

 render :json => { :conns => @conns, :status => :success } 

If you need to host multiple types of responses using the bright and shiny new respond_with method, you can create a class that responds to as_json :

 class JsonResponse def initialize(data,status) @data = data @status = status end def as_json(options={}) { :data => @data, :status => @status } end end 

Then name it like this:

 @conns = Connection.all respond_with(JsonResponse.new(@conns,"success")) 
+8
source

All Articles