Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails respond_with is not outputting the status of the rest call

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!

like image 498
Danny Avatar asked Dec 28 '22 05:12

Danny


2 Answers

: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"))
like image 108
zetetic Avatar answered Jan 14 '23 03:01

zetetic


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.

like image 33
oma Avatar answered Jan 14 '23 04:01

oma