ruby-on-rails – 如何将Hash传递给Grape API方法?
发布时间:2020-12-17 02:23:25  所属栏目:百科  来源:网络整理 
            导读:我遇到了Grape gem和参数验证方面的问题. 这背后的想法是通过API服务使用嵌套属性创建复杂实体. 我有一个创建旅行的方法,旅行有很多目的地,我想使用哈希传递目的地(使用accepts_nested_attributes_for助手). 我对参数有这个葡萄限制: requires :destination
                
                
                
            | 
 我遇到了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限制,因为目标是数组,而不是哈希: 
  
  
  requires :destinations,type: Array 发送请求时,您不需要“目标”哈希: { destinations => [ 
  { name => 'dest1',other_attribute: 'value',etc... },{ name => 'dest2',{ name => 'dest3',etc... }
]}这会创建一个哈希数组. 为了通过POSTMAN发送它,你需要修改那些目的地param你的发送并在POSTMAN中添加多行.就像是: destinations[][name] 'dest1' destinations[][other_attribute] 'value1' destinations[][name] 'dest2' destinations[][other_attribute] 'value2' destinations[][name] 'dest3' destinations[][other_attribute] 'value3' 希望这能回答你的问题.如果这是您正在寻找的,请告诉我. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
