ruby-on-rails - 根或嵌套对象中的 Rails 强参数
问题描述
我希望能够在根参数对象中支持一组参数:
?foo=a
params.permit(:foo)
或者在嵌套对象中:
?bar[foo]=a
params.require(:bar).permit(:foo)
我将参数从表单对象传递到该控制器,因此嵌套对象自然发生,但我也希望能够在查询字符串中传递根对象中的参数并支持两者。
有没有一种优雅的,非hacky的方式来实现这一点?
解决方案
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)
推荐阅读
- php - 更改数组 PHP 中的值
- excel - 循环浏览文件夹中的所有工作簿 - 复制并粘贴到母版
- buildfire - 使用 Buildfire Navgation 的 navigateTo 到需要用户购买的插件
- javascript - Material UI 和 Next.js - 动态样式不起作用
- c# - unity3d boxcollider2d 不与 Vector2.MoveTowards 碰撞
- uwp - 如何在 UWP 中为 NumberBox 应用 PercentFormatter?
- c++ - 随机但快速地遍历数组
- python - Flask-SQLAlchemy - 从用户关注的工作中获取最后的报价
- visual-studio-code - 如何在后台从命令行启动 vscode?
- laravel - Laravel 中的 Google Pay 或 Phone Pay 或 Paytm UPI API 支付