skp*_*rin 10 ruby-on-rails strong-parameters
在我的Rails控制器中使用强参数,如何声明允许的参数可以是a String还是Array?
我强大的参数:
class SiteSearchController < ApplicationController
[...abbreviated for brevity...]
private
def search_params
params.fetch(:search, {}).permit(:strings)
end
end
Run Code Online (Sandbox Code Playgroud)
我想要POST字符串搜索为String或作为Array:
要搜索一件事:
{
"strings": "search for this"
}
Run Code Online (Sandbox Code Playgroud)
或者,搜索多个东西:
{
"strings": [
"search for this",
"and for this",
"and search for this string too"
]
}
Run Code Online (Sandbox Code Playgroud)
更新:
目的:我正在创建一个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"
]
}
]
Run Code Online (Sandbox Code Playgroud)
或在一个页面上:
{
"page": "/section/look-at-this-page",
"strings": "search for this"
}
Run Code Online (Sandbox Code Playgroud)
(这将使我需要强大的参数允许一个Object或一个Array被发送.
这似乎是一个基本的东西,但我没有看到任何东西.
我知道我可以让stringsparam成为一个数组,然后需要在数组中搜索一个只有1个值的东西......但是我希望这个参数比那个更健壮.
tom*_*non 18
您可以只允许参数两次 - 一次用于数组,一次用于标量值.
def search_params
params.fetch(:search, {}).permit(:strings, strings: [])
end
Run Code Online (Sandbox Code Playgroud)
Eye*_*dic 10
您可以检查是否params[:strings]是一个数组并从那里开始工作
def strong_params
if params[:string].is_a? Array
params.fetch(:search, {}).permit(strings: [])
else
params.fetch(:search, {}).permit(:strings)
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4690 次 |
| 最近记录: |