【问题标题】:Rails Strong Parameters - Allow parameter to be an Array or StringRails 强参数 - 允许参数为数组或字符串
【发布时间】:2017-09-14 14:05:09
【问题描述】:

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

我的强参数:

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

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

我想将POST 字符串搜索为String 或Array:

要搜索 1 件事:

{
    "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"
        ]
    }
]

OR 在单个页面上:

{
    "page": "/section/look-at-this-page",
    "strings": "search for this"
}

(这将使我需要强参数允许发送Object 或Array。

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

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

【问题讨论】:

    标签: ruby-on-rails strong-parameters


    【解决方案1】:

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

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

    【讨论】:

    • 我没有测试过这个,但这很聪明。谢谢@tombeynon!
    • 实际上甚至可以像这样允许多种类型:params.permit(:attr, { :attr =&gt; [] }, { :attr =&gt; {} })。然而,尽管我很喜欢这种行为,但我在文档中的任何地方都找不到它......不过它可以工作。
    • 太棒了!绝对不会想到的! :D
    【解决方案2】:

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

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

    【讨论】:

    • 哦,太棒了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多