41

我有一个 API 可以让你销毁一个对象。我不确定的部分是记录被销毁后应该呈现什么 JSON。这里有几个选项,但我不确定最佳实践是什么。

版本 1:

返回具有 204 状态的空对象

def destroy
  item = current_user.current_cart.items.find(params[:id])
  item.destroy
  render json: {}, status: :no_content
end

版本 2:

归还物品,即使它已被销毁

def destroy
  item = current_user.current_cart.items.find(params[:id])
  item.destroy
  render json: item
end

其中一个是否优于另一个?有没有我没有想到的可能是首选的版本?

4

2 回答 2

33

对于删除请求,http 状态码 200 或 204 表示资源已成功删除。

9.7 删除

如果响应包含描述状态的实体,则成功的响应应该是 200(OK),如果操作尚未制定,则为 202(已接受),或者如果操作已经制定但响应不包括,则应为 204(无内容)一个实体。

因此,您可以返回带有 200 状态代码的对象或带有 204 状态代码的空响应

于 2013-06-13T17:45:38.433 回答
32

成功状态 204(无内容)似乎是合适的。正如 204 所暗示的那样,不能有响应主体,这可以通过render :nothing, status: :no_content或更吸引人的方式来实现:

def destroy
  item.destroy
  head :no_content
end

编辑: render :nothing自 Rails 5.1 以来已被弃用并被删除。相反,您可以使用render body: nil, status: :no_content.

于 2015-11-19T13:53:15.507 回答