【问题标题】:Rails - Array of hashes in Grape APIRails - Grape API 中的哈希数组
【发布时间】:2016-10-11 03:16:17
【问题描述】:

我真的是 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

【问题讨论】:

  • 我也需要,你找到什么解决方案了吗?

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


【解决方案1】:

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

对于一个块、组、要求和可选接受一个额外的选项类型,它可以是 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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多