[英]Rails RABL: how to respond with specified http status code?
基本上我有以下 controller 方法:
def create
begin
@check_in = create_check_in()
rescue => exception
render json: { message: exception }, status: 500
end
end
和以下 json.rabl 文件:
object @check_in => :event_check_in
attributes :id
我嘗試實現的是手動設置響應的 HTTP 狀態代碼。 它目前以 200 響應,我需要它改為 201。
我很少看到類似的問題,答案通常是從 controller 操作中渲染/響應,所以我嘗試了這樣的事情:
def create
begin
@check_in = create_check_in()
render @check_in, status: 201
rescue => exception
render json: { message: exception }, status: 500
end
end
但我所有的嘗試都失敗了,拋出了各種錯誤。
有沒有辦法設置狀態碼?
問題是當它期望第一個參數是 hash 選項(包括status
選項)時,您將@check_in
作為render
方法的第一個參數傳遞。
您的status: 201
選項作為 hash 傳遞給方法的第二個參數並被忽略。
通常渲染調用看起來像這樣:
render json: @check_in.as_json, status: 201
# or more commonly something like
render action: :create, status: 201 # the @check_in variable is already accessible to the view and doesn't need to be passed in
# or just
render status: 201
# since by default it will render the view with the same name as the action - which is `create`.
調用 render 的方式有很多種,更多信息請查看文檔。
-- 編輯 -- Max 有一個很好的評論 - 我強烈建議不要從所有異常中解救,也不要在特定的 controller 操作中這樣做。 除了他的建議之外,Rails 5+ 還支持:api 開箱即用的異常格式化,或者,如果您需要更多,我會看一下這樣的指南。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.