2016-10-11 137 views
1

哈希陣列我真的很新的傢伙Rails的,在我的項目,我想提出一個JSON字符串葡萄API。正如你所看到的,我的JSON有一個包含許多對象的user數組。我怎樣才能在我的葡萄中定義它?
謝謝導軌 - 葡萄API

{ 
    "users":[ 
     { 
      "first_name":"Brittany", 
      "last_name":"Chen", 
      "email":"[email protected]", 
      "phone_number":"+29-46-957-15423" 
     }, 
     { 
      "first_name":"Lynn", 
      "last_name":"Brooks", 
      "email":"[email protected]", 
      "phone_number":"+84-95-185-00137" 
     }, 
     { 
      "first_name":"Claire", 
      "last_name":"Paul", 
      "email":"[email protected]", 
      "phone_number":"+66-64-893-53401" 
     }, 
     { 
      "first_name":"Gemma", 
      "last_name":"Carter", 
      "email":"[email protected]", 
      "phone_number":"+83-46-325-54538" 
     } 
    ], 
    "service_ids":["1", "2", "3"], 
    "auth_token":"xxxxxxxxxxxxxxxxxxxxxx" 
} 

這是我的葡萄葡萄PARAMS

params do 
    optional :user, type: Hash do 
     optional :email, type: String, desc: "user email" 
     optional :first_name, type: String, desc: "user first name" 
     optional :last_name, type: String, desc: "user last name" 
     optional :phone_number, type: String, desc: "user phone number" 
    end 
    optional :service_ids, type: Array[Integer], desc: "list of service ids selected" 
    requires :auth_token, type: String, desc: "authentication_token" 
end 
+0

我需要同樣的解決方案嗎? –

回答

1

這就是所謂的 「嵌套參數的驗證」。在代碼中,你實際上需要的含可選參數emailfirst_namelast_namephone_number一個user散,所以不正是你所期待的。

使用塊,組,要求和可選接受額外的選項類型,可以是數組或哈希,並且默認爲數組。 根據值,嵌套參數將被視爲哈希值或數組中的哈希值。

來源:https://github.com/ruby-grape/grape#validation-of-nested-parameters你的情況

所以,你將不得不這樣描述您的PARAMS:

params do 
    optional :users, type: Array do 
    optional :email,  type: String, desc: "user email" 
    optional :first_name, type: String, desc: "user first name" 
    optional :last_name, type: String, desc: "user last name" 
    optional :phone_number, type: String, desc: "user phone number" 
    end 
    # ... 
    # any other params 
    # ... 
end 

這樣一來,陣列中的每個項目將有望匹配給定塊中的字段。