使用rails-api
:
def show
render json: Room.find(params[:id])
end
这在找到资源时有效。但是寻找一个不存在的返回500错误。这不应该归还404?
> http --json GET chat.dev/api/v1/rooms/23
HTTP/1.1 500 Internal Server Error
Connection: close
Content-Type: text/plain; charset=utf-8
X-Request-Id: 4cd2ba9f-0f85-4530-9c0a-0ef427ac5b31
X-Runtime: 0.094633
ActiveRecord::RecordNotFound at /api/v1/rooms/23
================================================
> Couldn't find Room with id=23
app/controllers/api/v1/rooms_controller.rb, line 20
---------------------------------------------------
``` ruby
15 # render :json => {}, :status => :not_found
16 # end
17 # end
18
19 def show
> 20 render json: Room.find(params[:id])
21 end
22
23 end
24
25 end
答案 0 :(得分:5)
刚遇到同样的事情。在常规的Rails中,而不是rails-api。希望得到更好的东西,但到目前为止我只是做(如上所示):
def show
render json: Room.find(params[:id])
rescue ActiveRecord::RecordNotFound
render json: {}, status: :not_found
end
我认为如果您考虑Rails的“救援并仅在生产中返回404”作为一个方便的默认设置,这是合理的,但是当您更关心状态代码时,您需要得到一些手(和代码)脏。
答案 1 :(得分:1)