6

I have a Photo class that has a "name" attribute and a "tags" attribute. My goal is to implemented an update function in Rails that replaces the photo's tags with whatever was inputted. 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.

However, when I submit an empty array through HTTParty as one of the body parameters, I believe that HTTParty is translating [] into nil. Therefore the photos#update endpoint on my Rails backend receives nothing for the parameter "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.

Donald Huh
  • 61
  • 2

2 Answers2

1

This is a bug/feature in Rails 4, you can read more about the drama at: https://github.com/rails/rails/issues/13420

Your options include:

  • One-off hack similar to @mkk's answer
  • Upgrade to Rails 5
  • Disable deep_munge everywhere, and deal with the consequences of that:

>

# config/application.rb
config.action_dispatch.perform_deep_munge = false
Meekohi
  • 10,390
  • 6
  • 49
  • 58
  • P.S. to clarify -- this is not really a problem with HTTParty, it's a problem with your Rails backend converting `[]` into `nil` for security reasons. – Meekohi Jan 31 '17 at 21:01
-1

just assign empty array to params, for example:

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

it will assign empty array if params[:photo][:tags] is not set already. 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]. 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 :)

mkk
  • 7,583
  • 7
  • 46
  • 62
  • The question is how can i bypass the httparty conversion of empty array to nil param. – Mohanraj May 06 '14 at 11:25
  • @Mohanraj that's the way how you deal with this. If nothing is being sent [ i.e. ``nil`` instead of an empty array ], you just have to set it manually. I'm sorry this does not satisfies your needs, but I am confident this is the correct answer (or rather: workaround ). – mkk May 06 '14 at 14:49
  • No, when we set params[:photo][:tags] ||= [] in the httparty request, absolutely i am not receiving params[:photo][:tags] => nil as well. – Mohanraj May 06 '14 at 17:52
  • @Mohanraj that's not the issue. Here is the issue. An ``object`` belongs to ``category``, and in UI you have many checkboxes. Assuming you are in edit action, some of the checkboxes are checked. The issue is, that if you uncheck all checkboxes and submit a form, the param that represents set of categories to which object belongs is ``nil``, not ``[]``, so your action will be ignored and nothing will change. The solution is to manually set this parameter to ``[]`` in controller if it's ``nil``. This way the object will be updated correctly and won't belong to any category. – mkk May 06 '14 at 18:12