4

我在使用 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 方法。

这是一个屏幕截图:在此处输入图像描述

如果有人可以帮助我,我将不胜感激。

4

1 回答 1

2

从您要发送的内容来看,您需要更改 Grape 限制,因为destinations是 a Array,而不是 a 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'

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

于 2014-10-30T12:18:00.740 回答