Strong Rails Options - Allow a parameter to be an array or string

Using Strong parameters in my Rails controller, how can I say that the allowed parameter can be String or Array ?

My strong options are:

 class SiteSearchController < ApplicationController [...abbreviated for brevity...] private def search_params params.fetch(:search, {}).permit(:strings) end end 

I want to POST string to search as a String or as an Array :

Search 1 things:

 { "strings": "search for this" } 

OR, to search for a few things:

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

Update:

Purpose: I create an API where my users can โ€œdownloadโ€ requests (receive responses via web-hooks ) or make a one-time request (receive an immediate response) to the same endpoint. This question is only 1 small part of my requirement.

The following snippet will perform the same logic, where I will allow the search on several pages, i.e.:

 [ { "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 one page:

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

(which will make me have Strong pairs to send an Object or Array .

This seems like a basic thing, but I don't see anything there.

I know that I can just make the strings array an array, and then require looking for 1 thing to have only 1 value in the array ... but I want this parameter to be more reliable than that.

+5
source share
2 answers

You can check if params[:strings] array and work from there

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

You can simply enable the parameter twice - once for the array and once for the scalar value.

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

Source: https://habr.com/ru/post/1266871/


All Articles