Rails 强参数 - 允许参数为数组或字符串

Rails Strong Parameters - Allow parameter to be an Array or String

在我的 Rails 控制器中使用 强参数 ,我如何声明允许的参数可以是 StringArray

我的强参数:

class SiteSearchController < ApplicationController
    [...abbreviated for brevity...]

    private
    def search_params
        params.fetch(:search, {}).permit(:strings)
    end
end

我想要 POST 个字符串作为 StringArray:

进行搜索

要搜索 1 个东西:

{
    "strings": "search for this"
}

或者,搜索多个内容:

{
    "strings": [
        "search for this",
        "and for this",
        "and search for this string too"
    ]
}

更新:

目的: 我正在创建一个 API,我的用户可以在其中 "batch" 请求(通过 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"
}

(这将使我需要 强参数 允许发送 ObjectArray

这似乎是一个基本的东西,但我没有看到任何东西。

我知道我可以让 strings 参数成为一个数组,然后需要搜索 1 个东西以在数组中只有 1 个值...但我想让这个参数更健壮比那个。

您可以检查 params[:strings] 是否是数组并从那里开始工作

def strong_params
  if params[:string].is_a? Array
    params.fetch(:search, {}).permit(strings: [])
  else 
    params.fetch(:search, {}).permit(:strings)
  end
end

您可以只允许该参数两次 - 一次用于数组,一次用于标量值。

def search_params
    params.fetch(:search, {}).permit(:strings, strings: [])
end