Reputation: 3759
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?
Upvotes: 23
Views: 24686
Reputation: 6763
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.
Upvotes: 30