如何验证路径参数并在Rails中显式设置状态代码

时间:2017-03-27 14:23:08

标签: ruby-on-rails ruby controller http-status-codes

我正在尝试设置一个超级简单的RESTful端点(作为ApplicationController),它执行简单的路径参数验证并返回硬编码的JSON响应:

{
  "foo" : "123",
  "bar" : {
    "whistle" : "feather",
    "ping" : "pong"
  }
}

被点击的网址为GET http://localhost/widgets/${widgetId}/${fizzbuzzId},其中${widgetId}${fizzbuzz}都应为正整数。

我试图找出如何检查${widgetId}${fizzbuzzId}的值,如果它们不是正整数则抛出400。我还试图找出如何将硬编码的response字符串作为HTTP响应实体返回状态代码为200,如果两个路径参数在验证后仍然存在:

routes.rb

resource :widgets

然后是控制器:

class WidgetsController < ApplicationController
  def show
    if(params[:widgetId].to_i <= 0 || params[:fizzbuzzId] <= 0) {
      render json: { "error" : "bad path params" }, status: :not_found
      return
    }

    response = %(
      {
        "foo" : "123",
        "bar" : {
          "whistle" : "feather",
          "ping" : "pong"
        }
      }
    )

    render json: response, status: :ok 
  end
end

当我跑步时,我得到:

myuser:myapp myuser$ curl -k http://localhost:3000/widgets

SyntaxError at /widgets
==============================

> syntax error, unexpected '{', expecting keyword_then or ';' or '\n'
/Users/myuser/myapp/app/controllers/widgets_controller.rb:4: syntax error, unexpected ':', expecting =>
      render json: { "error" : "bad path params ...
                              ^
/Users/myuser/myapp/app/controllers/widgets_controller.rb:4: syntax error, unexpected '}', expecting keyword_end
...ad path params" }, status: :not_found
...                               ^
/Users/myuser/myapp/app/controllers/widgets_controller.rb:6: syntax error, unexpected '}', expecting keyword_end

app/controllers/widgets_controller.rb, line 3
----------------------------------------------------

``` ruby
    1   class WidgetsController < ApplicationController
    2     def show
>   3       if(params[:widgetId].to_i <= 0 || params[:fizzbuzzId] <= 0) {
    4         render json: { "error" : "bad path params ID" }, status: :not_found
    5         return
    6       }
    7   
    8       response = %(
```

App backtrace
-------------

 - app/controllers/widgets_controller.rb:3:in `'
 - app/middleware/catch_json_parse_errors.rb:8:in `call'

Full backtrace

我出错的任何想法?

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法检查您的参数是否为正整数:

>> "23".to_i > 0
=> true
>> "foo".to_i > 0
=> false

所以你可以通过params[:widgetId].to_i > 0为你的参数娴熟 这对你有意义吗?

此外,如果您想要返回错误响应,则需要“提前”返回,否则控制器会抱怨双重渲染:

render json: { "error" : "bad input" }, status: :400 and return