【问题标题】:How to pass a Hash to Grape API method?如何将哈希传递给 Grape API 方法?
【发布时间】:2014-10-30 01:22:59
【问题描述】:

我在使用 Grape gem 和参数验证时遇到问题。 这背后的想法是通过 API 服务使用嵌套属性创建一个复杂的实体。

我有一种创建旅行的方法,旅行有很多目的地,我想使用散列传递这些目的地(使用 accepts_nested_attributes_for 助手)。

我对参数有这个葡萄限制:

requires :destinations, type: Hash

我正在尝试发送这样的内容:

{ destinations => [ 
  { destination: { name => 'dest1'} },
  { destination: { name => 'dest2'} }, 
  { destination: { name => 'dest3'} }
]}

为了在方法内部构建类似下面的结构并创建行程:

{ trip: {
  name: 'Trip1', destinations_attributes: [
    { name: 'dest1' },
    { name: 'dest2' },
    { name: 'dest3' }
  ]
}}

我正在使用 POSTMAN chrome 扩展来调用 API 方法。

这是一个屏幕截图:

如果有人可以帮助我,我将非常感激。

【问题讨论】:

  • 在编辑您的帖子期间,我发现您错过了一个大括号(在destination3 之后),使您的哈希成为无效结构。这是一个原因吗?

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


【解决方案1】:

根据您要发送的内容,您需要更改 Grape 限制,因为 destinationsArray,而不是 Hash

requires :destinations, type: Array

发送请求时不需要“目标”哈希:

{ destinations => [ 
  { name => 'dest1', other_attribute: 'value', etc... },
  { name => 'dest2', other_attribute: 'value', etc... }, 
  { name => 'dest3', other_attribute: 'value', etc... }
]}

这会创建一个哈希数组。

为了通过 POSTMAN 发送此信息,您需要修改您的发送参数 destinations 并在 POSTMAN 中添加多行。比如:

destinations[][name]                'dest1'
destinations[][other_attribute]     'value1'
destinations[][name]                'dest2'
destinations[][other_attribute]     'value2'
destinations[][name]                'dest3'
destinations[][other_attribute]     'value3'

希望这能回答您的问题。让我知道这是否是您想要的。

【讨论】:

    猜你喜欢
    • 2016-08-13
    • 2013-11-27
    • 2012-08-25
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    相关资源
    最近更新 更多