Rails - Grape API中的哈希数组

时间:2016-10-11 03:16:18

标签: ruby-on-rails json grape grape-api

我真的是Rails的新手,在我的项目中,我想向Grape API提交一个JSON字符串。如您所见,我的JSON有一个包含许多对象的user数组。如何在我的葡萄中定义它? 谢谢

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

这是我的Grape 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

1 个答案:

答案 0 :(得分:1)

这称为"验证嵌套参数"在葡萄。在您的代码中,您实际上要求的user哈希包含可选参数emailfirst_namelast_namephone_number,因此不完全是您正在查找的内容对

  

使用块,组,要求和可选接受其他选项类型,可以是Array或Hash,默认为Array。 根据值,嵌套参数将被视为散列值或数组中散列值。

来源:https://github.com/ruby-grape/grape#validation-of-nested-parameters

所以在你的情况下,你必须像这样描述你的参数:

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

因此,数组中的每个项目都应与给定块中的字段匹配。