我在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方法。
这是一个屏幕截图:
如果有人可以帮助我,我将不胜感激。
根据要发送的内容,您需要更改Grape限制,因为destinations
是Array
,而不是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'
希望这能回答您的问题。让我知道这是否是您想要的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句