首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Rails3中返回空JSON响应的首选方法是什么?

在Rails3中返回空JSON响应的首选方法是什么?
EN

Stack Overflow用户
提问于 2012-11-27 20:14:12
回答 1查看 22K关注 0票数 20

当用户在Rails3应用程序的/update/ action中发布JSON时,最好的响应方式是什么?

我只想发送一个带有200代码的空JSON响应,类似于

代码语言:javascript
复制
head :no_content

代码语言:javascript
复制
render :nothing => true, :status => 204

(来自How to return HTTP 204 in a Rails controller的示例)。

通常我都是这样做的:

代码语言:javascript
复制
render :json => {}

代码语言:javascript
复制
render :json => 'ok'

有没有更好的或者更多的Rails-y方法呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-29 02:39:34

我的Rails3应用程序使用这样的代码进行更新。html和xml的代码是由Rails自动生成的,所以我只是使用相同的格式添加了JSON渲染器。

代码语言:javascript
复制
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

完美工作,这才是最重要的。

票数 29
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13584025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档