Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way to return an empty JSON response in Rails 3?

When a user POSTs JSON to the /update/ action in a Rails 3 app, what is the best way to respond?

I want to just send an empty JSON response with a 200 code, something like

head :no_content

or

render :nothing => true, :status => 204

(examples from How to return HTTP 204 in a Rails controller).

Typically I have been doing this:

render :json => {}

or

render :json => 'ok'

Is there preferred or more Rails-y way to this?

like image 640
Marc O'Morain Avatar asked Nov 27 '12 12:11

Marc O'Morain


Video Answer


1 Answers

My Rails 3 app uses code such as this for updates. The code for html and xml was auto generated by Rails, so I just added in the JSON renderer using the same format.

respond_to do |format|
  if @product.update_attributes(params[:product])
    format.html { redirect_to(@product, :notice => 'Product was successfully updated.') }
    format.xml  { head :ok }
    format.json { head :ok }
  else
    format.html { render :action => "edit" }
    format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
    format.json { render :json => @product.errors, :status => :unprocessable_entity }
  end
end

Works perfectly, which is what's ultimately important.

like image 143
Snips Avatar answered Oct 09 '22 07:10

Snips