繁体   English   中英

Rails - Grape API 中的哈希数组

[英]Rails - Array of hashes in Grape API

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

{
    "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"
}

这是我的葡萄参数

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

这在 Grape 中称为“嵌套参数的验证”。 在您的代码中,您实际上是在要求包含可选参数emailfirst_namelast_namephone_numberuser哈希,所以这不是您想要的。

对于块,组,需要和可选接受额外的选项类型,可以是数组或哈希,默认为数组。 根据值,嵌套参数将被视为散列值或数组中的散列值。

来源: 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM