I am trying to make a simple rest api with rails using the respond_with method, but it does not want to output any type of status message
for example, I want it to not only return the json for a get call but also a ok status. The same for when a post or delete works/fails.
Several tutorials suggest using additional :status parameters but they don't seem to affect the output at all.
def index
@conns = Connection.all
respond_with(@conns, :status => :ok)
end
This returns the same exact thing as if :status => :ok was not there.
Any ideas??
Thanks!
:status => :ok
sets the status code of the HTTP header, i.e. it's the same as :status => 200
. If you want to add something to the response body, you'll need to add it explicitly, e.g.
respond_with({:conns => @conns, :status => :success}.to_json)
EDIT
OK, so that doesn't work. If you don't need to respond to anything but JSON, you could just use good old render
:
render :json => { :conns => @conns, :status => :success }
If you have to accommodate multiple response types with the bright and shiny new respond_with
method, you could make 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 call it like so:
@conns = Connection.all
respond_with(JsonResponse.new(@conns,"success"))
This is because it would implicitly return :status => :ok
, when the response is ok, which I guess it is :)
Try with another status code, like
:status => :not_found
There's a full list of status codes in the official ruby on rails guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With