2017-05-23 92 views
1

是否可以針對Grape中的每個數組元素運行自定義驗證器?我知道我可以用我的驗證器驗證整個數組,但我認爲如果我爲每個元素使用它,錯誤消息會更好。Grape:數組中每個元素的自定義驗證器

我的參數是這樣的:

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

隨着requires :conditions, type: Array, valid_conditions: true驗證運行整個陣列。我能得到最好的結果嗎?

回答

0

這是完全可能的,您可以在響應中聲明特定鍵的值。

assert_equal some_obj[0].first[1], "interests" 

這裏是IRB

Success weeds out the uncommitted ~ irb 
2.2.3 :001 > a = [{:field=>"interests", :operator=>"any", :value=>["cars", "cats"]}] 
=> [{:field=>"interests", :operator=>"any", :value=>["cars", "cats"]}] 
2.2.3 :002 > a[0].first 
=> [:field, "interests"] 
2.2.3 :003 > a[0].first[1] 
=> "interests" 
2.2.3 :004 > 
0

是有可能同樣的事情,但你必須使用一個自定義的驗證。

下面是一個例子

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