Rails - 带有空数组的强参数 [英] Rails - Strong parameters with empty arrays

查看:30
本文介绍了Rails - 带有空数组的强参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向我的控制器发送一组关联 ID,比如 foo_ids.为了允许一组值,我使用:

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: [])

现在,问题是如果我发送一个空数组 foo_ids,参数将被忽略.不是像空数组那样清除所有 foos,而是单独保留关联,因为 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.

这可能是因为 一个空数组在 rails 中转换为 nil,并且该 nil 值被忽略,因为强参数正在寻找一组标量值,而不是单个标量值.

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!

其他信息

在更新控制器操作中,我需要能够处理两种情况.我需要能够将 foo_ids 设置为空数组.如果我只想更新另一个字段,我还需要能够忽略 foo_ids.如果 nil 不适用于第二种情况,则将 foo_ids 设置为空数组.

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.

推荐答案

我想到的临时解决方案是:

The temporary solution I've come down to is:

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

此处,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.

这篇关于Rails - 带有空数组的强参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆