Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby Grape:数组中每个元素的自定义验证器_Ruby_Validation_Grape_Grape Api - Fatal编程技术网

Ruby Grape:数组中每个元素的自定义验证器

Ruby Grape:数组中每个元素的自定义验证器,ruby,validation,grape,grape-api,Ruby,Validation,Grape,Grape Api,是否可以对Grape中数组的每个元素运行自定义验证器?我知道我可以用验证器验证整个数组,但我认为如果我对每个元素使用它,错误消息会更好 我的参数如下所示: "conditions": [ { "field": "interests", "operator": "any", "value": ['cars', 'cats'] }, { "field": "age",

是否可以对Grape中数组的每个元素运行自定义验证器?我知道我可以用验证器验证整个数组,但我认为如果我对每个元素使用它,错误消息会更好

我的参数如下所示:

  "conditions": [
      {
          "field": "interests",
          "operator": "any",
          "value": ['cars', 'cats']
      },
      {
          "field": "age",
          "operator": "gt",
          "value": 25
      }
  ]

使用
requires:conditions,type:Array,valid\u conditions:true
将为整个数组运行验证程序。这是我能得到的最好结果吗?

这是完全可能的,您可以在响应中断言特定键的值

assert_equal some_obj[0].first[1], "interests" 
在irb中也有同样的情况

 Yes it's possible, but you have to use a custom validator. 

Here is an example

class Validator < Grape::Validations::Base
  def validate_param!(attr_name, params)
    unless params[attr_name].each { //your code here }
      fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: 'your message'
    end
  end
end

这是完全可能的,您可以在响应中断言特定键的值

assert_equal some_obj[0].first[1], "interests" 
在irb中也有同样的情况

 Yes it's possible, but you have to use a custom validator. 

Here is an example

class Validator < Grape::Validations::Base
  def validate_param!(attr_name, params)
    unless params[attr_name].each { //your code here }
      fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: 'your message'
    end
  end
end

是的,这是可能的,但您必须使用自定义验证器

这里有一个例子

requires :conditions, type: Array, validator: true

是的,这是可能的,但您必须使用自定义验证器

这里有一个例子

requires :conditions, type: Array, validator: true