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

Rails RABL: how to respond with specified http status code?

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

  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的方式有很多种,see the docs for more

-- 编辑 -- Max 有一个很好的评论——我强烈建议不要从所有异常中解救,也不要在特定的控制器操作中这样做。除了他的建议,Rails 5+ supports :api formatting for exceptions out of the box or, if you need more, I'd look at a guide like this one.