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.
This is quite late, but I just had this problem myself. I solved it by including both the scalar version and array version in the permit statement, like so:
params.require(:photo).permit(:tags, tags: [])
FYI - it has to have both in the same permit statement - if you chain them it'll get thrown out for some reason.
EDIT: I just noticed that an empty array submitted via this method will be turned into nil - I've now got a bunch of fields that should be empty arrays that are nil. So the solution I posted doesn't actually work for me.
EDIT the second: Thought I had already added this, but this problem is related to Rails performing deep_munge on params hashes. This comment explains how to fix it: https://stackoverflow.com/a/25428800/130592