简体   繁体   English

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

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

Using Strong Parameters in my Rails Controller, how can I state that a permitted parameter can be a String or an Array ? 在我的Rails控制器中使用强参数 ,如何声明允许的参数可以是String还是Array

My strong params: 我强大的参数:

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

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

I'm wanting to POST string(s) to search as a String or as an Array : 我想要将字符串POST作为StringArray进行搜索:

To search for 1 thing: 要搜索一件事:

{
    "strings": "search for this"
}

OR, to search for multiple things: 或者,搜索多个东西:

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

Update: 更新:

Purpose: I'm creating an API where my users can "batch" requests (getting responses via web-hooks ), or make a one-off request (getting an immediate response) all on the same endpoint. 目的:我正在创建一个API,我的用户可以“批量”请求(通过web-hooks获取响应),或者在同一个端点上发出一次性请求(立即获得响应)。 This question is only 1 small part of my requirement. 这个问题只是我要求的一小部分。

The next piece will be doing this same logic, where I'll allow the search to happen on multiple pages, ie: 下一篇文章将使用相同的逻辑,我将允许搜索在多个页面上进行,即:

[
    {
        "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 on a single page: 或在一个页面上:

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

(which will make me need to have Strong Params allow an Object or an Array to be sent. (这将使我需要强Params允许发送ObjectArray

This seems like a basic thing, but I'm not seeing anything out there. 这似乎是一个基本的东西,但我没有看到任何东西。

I know that I could just make the strings param an array, and then require searching for 1 thing to just have 1 value in the array... but I want to have this parameter be more robust than that. 我知道我可以让strings param成为一个数组,然后需要搜索1个东西才能在数组中只有1个值......但是我希望这个参数比这更健壮。

You can just permit the parameter twice - once for an array and once for a scalar value. 您可以只允许参数两次 - 一次用于数组,一次用于标量值。

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

You could check if params[:strings] is an array and work from there 您可以检查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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM