Rails - Strong parameters with empty arrays

ruby-on-rails, strong-parameters

Solution

The temporary solution I've come down to is:

params[:foo_ids] ||= [] if params.has_key?(:foo_ids)
params.permit(foo_ids: [])

Here, `foo_ids` is set to an empty array only if is passed. If it is not passed in the request, it is ignored.

I'm still hoping to find a better solution to this, as this sort of thing will be quite common in the project I'm working on - please do suggest better ideas if you have any.

Problem

I'm sending an array of association ids, say `foo_ids` to my controller. To permit an array of values, I use: ``` params.permit(foo_ids: []) ``` Now, the problem is that if I send an empty array of `foo_ids`, the parameter is ignored. Instead of clearing all `foos` as an empty array should do, the association is left alone, because `foo_ids` isn't permitted. This may be because an empty array is converted to nil in rails, and that nil value is ignored as strong parameters is looking for an array of scalar values, not a single scalar value. Can anyone suggest a good way to solve this? Thanks! Additional info In an update controller action, I need to be able to handle two cases. I need to be able to set `foo_ids` to an empty array. I also need to be able to ignore `foo_ids` if I merely want to update another field. Setting `foo_ids` to an empty array if nil does not work for this second case.

Original source

Related problems