[英]Rails Strong Parameters - Allow parameter to be an Array or String
在我的Rails控制器中使用强参数 ,如何声明允许的参数可以是String
还是Array
?
我强大的参数:
class SiteSearchController < ApplicationController
[...abbreviated for brevity...]
private
def search_params
params.fetch(:search, {}).permit(:strings)
end
end
我想要将字符串POST
作为String
或Array
进行搜索:
要搜索一件事:
{
"strings": "search for this"
}
或者,搜索多个东西:
{
"strings": [
"search for this",
"and for this",
"and search for this string too"
]
}
更新:
目的:我正在创建一个API,我的用户可以“批量”请求(通过web-hooks
获取响应),或者在同一个端点上发出一次性请求(立即获得响应)。 这个问题只是我要求的一小部分。
下一篇文章将使用相同的逻辑,我将允许搜索在多个页面上进行,即:
[
{
"page": "/section/look-at-this-page",
"strings": "search for this"
},
{
"page": "/this-page",
"strings": [
"search for this",
"and for this",
"and search for this string too"
]
}
]
或在一个页面上:
{
"page": "/section/look-at-this-page",
"strings": "search for this"
}
(这将使我需要强Params允许发送Object
或Array
。
这似乎是一个基本的东西,但我没有看到任何东西。
我知道我可以让strings
param成为一个数组,然后需要搜索1个东西才能在数组中只有1个值......但是我希望这个参数比这更健壮。
您可以只允许参数两次 - 一次用于数组,一次用于标量值。
def search_params
params.fetch(:search, {}).permit(:strings, strings: [])
end
您可以检查params[:strings]
是否是一个数组并从那里开始工作
def strong_params
if params[:string].is_a? Array
params.fetch(:search, {}).permit(strings: [])
else
params.fetch(:search, {}).permit(:strings)
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.