2017-05-23 12 views
1

ブドウの配列の各要素に対してカスタムバリデータを実行できますか?バリデーターで配列全体を検証できますが、各要素に使用するとエラーメッセージが改善されると思います。ブドウ:配列の各要素のカスタムバリデータ

私のパラメータは、次のようになります。

"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

にこれと同じものです。

requires :conditions, type: Array, validator: true 
:ここ

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 

あなたは、このようにそれを使用する例です。

関連する問題