【问题标题】:What is the preferred way to return an empty JSON response in Rails 3?在 Rails 3 中返回空 JSON 响应的首选方式是什么?
【发布时间】:2012-11-27 12:14:11
【问题描述】:

当用户将 JSON POST 到 Rails 3 应用程序中的 /update/ 操作时,最好的响应方式是什么?

我只想发送一个带有 200 代码的空 JSON 响应,例如

head :no_content

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

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

通常我一直在这样做:

render :json => {}

render :json => 'ok'

是否有首选或更多 Rails-y 方法?

【问题讨论】:

  • 你不应该用 204 返回任何东西。

标签: ruby-on-rails json http rest


【解决方案1】:

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

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

完美运行,这才是最重要的。

【讨论】:

  • head :no_content 和 head :ok 有什么区别?
  • @Donato :no_content (204) 响应是成功但未返回任何内容的请求,:ok (200) 是成功但也返回适当数据的请求。
猜你喜欢
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多