如何用ActionParameters确保Rails的page参数为整数而非数组?
如何确保Rails中GET请求的page参数为整数而非数组?
我们的应用接收商品列表查询的GET请求,支持page参数(要求为整数),示例请求:
http://localhost/products?page=2
现在需要确保该参数确实是整数,核心是要拦截类似以下数组形式的请求(这类请求会导致代码报错):
http://localhost/products?page[]=2
http://localhost/products?page[random_key]=2
已知在Rails中可以通过如下方式声明参数为数组:
要声明参数值必须为允许的标量值数组,可将键映射为空数组:
params.permit(id: [])
目前想到的简单处理方式是直接判断参数类型:
run_the_code unless params[:page].is_a?(Array) # 或者 run_the_code if params[:page].is_a?(Integer)
但有没有更简便的方式,比如利用ActionParameters API实现?比如类似这样的写法:
params.permit(page: :integer)
内容的提问来源于stack exchange,提问作者romanstrazanec
相关产品推荐
相关产品推荐

