如何制作可选的强参数键但过滤嵌套参数? [英] How to make an optional strong parameters key but filter nested params?

查看:34
本文介绍了如何制作可选的强参数键但过滤嵌套参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有这个:

params.require(:item).permit!

让我们假设这个 rspec 规范按预期工作:

Let's assume this rspec spec, which works as expected:

put :update, id: @item.id, item: { name: "new name" }

然而,以下原因导致ActionController::ParameterMissing:

put :update, id: @item.id, item: nil

它与我用于其他操作的控制器宏有关,通过它我无法控制正在发送的参数(宏检查用户凭据,所以我并不真正关心实际测试 #update 操作,而我只是为它测试 before_filters).

It has to do with controller macros that I use for other actions and through which I cannot control the params being sent (the macros checks for user credentials, so I don't really care about actually testing an #update action, rather I just test before_filters for it).

所以我的问题是:我如何使 params[:item] 成为可选的,但仍然过滤其中的属性(如果它存在)?

So my question is: How do I make params[:item] optional, yet still filter attributes within it if it's present?

推荐答案

关于:

params.require(:item).permit!if params[:item]

您不能要求可选参数.这是矛盾的.

You cannot require an optional parameter. That is contradictory.

正如 mtjhax 在他的评论中提到的,here 有建议使用fetch 代替:params.fetch(:item, {}).permit!

as mtjhax mentioned in his comment, there is advice from here to use fetch instead: params.fetch(:item, {}).permit!

这篇关于如何制作可选的强参数键但过滤嵌套参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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