简体   繁体   English

如何通过HTTParty通过PUT请求发送空数组?

[英]How do I send an empty array through a PUT request via HTTParty?

I have a Photo class that has a "name" attribute and a "tags" attribute. 我有一个Photo类,它具有“name”属性和“tags”属性。 My goal is to implemented an update function in Rails that replaces the photo's tags with whatever was inputted. 我的目标是在Rails中实现一个更新功能,用输入的内容替换照片的标签。 For example, if I try to PUT a JSON object that has "tags" set to [], I want any tags to be cleared from the photo. 例如,如果我尝试将“标签”设置为[]的JSON对象PUT,我希望从照片中清除任何标签。

However, when I submit an empty array through HTTParty as one of the body parameters, I believe that HTTParty is translating [] into nil. 但是,当我通过HTTParty提交一个空数组作为body参数之一时,我相信HTTParty正在将[]转换为nil。 Therefore the photos#update endpoint on my Rails backend receives nothing for the parameter "tags". 因此,我的Rails后端上的照片#update endpoint没有收到参数“tags”的任何内容。 I am looking for a way for HTTParty to not convert [] into nil because I lose the ability to remove tags from the photo. 我正在寻找一种方法让HTTParty不将[]转换为nil因为我失去了从照片中删除标签的能力。

This is a bug/feature in Rails 4, you can read more about the drama at: https://github.com/rails/rails/issues/13420 这是Rails 4中的错误/功能,您可以在以下网址阅读有关该剧的更多信息: https//github.com/rails/rails/issues/13420

Your options include: 您的选择包括:

  • One-off hack similar to @mkk's answer 一次性黑客类似于@ mkk的回答
  • Upgrade to Rails 5 升级到Rails 5
  • Disable deep_munge everywhere, and deal with the consequences of that: 在任何地方禁用deep_munge ,并处理其后果:

> >

# config/application.rb
config.action_dispatch.perform_deep_munge = false

just assign empty array to params, for example: 只需将空数组分配给params,例如:

params[:photo][:tags] ||= []

it will assign empty array if params[:photo][:tags] is not set already. 如果没有设置params [:photo] [:tags],它将分配空数组。 If it doesn't work, it means that you have to adjust keys, for example maybe you do not have :tags, but :tag_ids, then you will have to write params[:photo][:tags]. 如果它不起作用,则意味着你必须调整键,例如,你可能没有:tags,但是:tag_ids,那么你将不得不写params [:photo] [:tags]。 Just check your HTML structure ( you can always paste it here and I can help you ]. As far as I know this is the standard approach :) 只需检查您的HTML结构(您可以随时粘贴它,我可以帮助您)。据我所知这是标准方法:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM