首页 > 解决方案 > 根或嵌套对象中的 Rails 强参数

问题描述

我希望能够在根参数对象中支持一组参数:

?foo=a
params.permit(:foo)

或者在嵌套对象中:

?bar[foo]=a
params.require(:bar).permit(:foo)

我将参数从表单对象传递到该控制器,因此嵌套对象自然发生,但我也希望能够在查询字符串中传递根对象中的参数并支持两者。

有没有一种优雅的,非hacky的方式来实现这一点?

标签: ruby-on-railsstrong-parameters

解决方案


require is like [] with an exception when the value is missing (much like Hash#fetch). You can instead just use [] directly to get the nested structure if it's there, and fall back to the root params otherwise:

(params[:bar] || params).permit(:foo)

推荐阅读