Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `status: :ok` do in `render json:` (Rails)

What doesstatus: :ok do in render json: {round: @round}, status: :ok?

Sometimes everything works without it, but sometimes its necessary to prevent an error like,

ActionController::UnknownFormat (ActionController::UnknownFormat):

I use Angular for front-end and Rails for back-end.

My understanding is that this final line in the Rails controller action converts the server response back to json format so Angular can read it (not 100% confident this is correct explanation).

But I don't understand why to use one or the other of the following. Sometimes one works and sometimes the other does.

  1. render json: {round: @round}, status: :ok1
  2. respond_to :json and respond_with @round

Can anyone share some insight?

like image 743
tim_xyz Avatar asked Oct 18 '25 17:10

tim_xyz


2 Answers

What does status: :ok do in render json:

It means the response will be sent with 200 OK http response code.

like image 158
Marek Lipka Avatar answered Oct 20 '25 07:10

Marek Lipka


The status: :ok in render json: {round: @round}, status: :ok tells the render method to change the status code which is 200 OK by default in the HTTP header (Rendering in Rails Guide). So in case of :ok there should be no difference.

Your method invocation tells the render method to render the hash {round: @round} in json format with the status code 200 OK.

The api dock tells you more about the usage of respond_to which is used to distinguish between different content types while render does the heavy lifting of actually rendering your response.

like image 40
Johannes Thorn Avatar answered Oct 20 '25 08:10

Johannes Thorn