Rails RABL:如何响应指定的http状态码?



基本上我有以下控制器方法:

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代替。

我看到很少类似的问题,答案通常是渲染/respond_with从控制器的动作,所以我尝试这样做:

def create
begin
@check_in = create_check_in()
render @check_in, status: 201
rescue => exception
render json: { message: exception }, status: 500
end
end

但是我所有的尝试都失败了,抛出了各种错误。

我可以设置状态码吗?

问题是你在传递@check_in作为render方法的第一个参数时,它期望第一个参数是选项的哈希,包括status选项。

您的status: 201选项作为散列传递给方法的第二个参数并被忽略。

渲染调用通常看起来像这样:

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,更多方法请参阅文档。

——EDIT——Max有一个很好的评论-我强烈建议不要从所有异常中拯救,也不要在特定的控制器动作中这样做。除了他的建议之外,Rails 5+还支持:开箱即用的异常api格式化,或者,如果你需要更多,我会看看这样的指南。

相关内容

最新更新