Search code examples
ruby-on-railsstrong-parametersapplicationcontroller

Dynamic / Regex params in ApplicationController


How to permit dynamic params in an AppicationController?

so all these parameters should permitted:

params = { "filter_color" => "blue,green", 
           "filter_size" => "xl,sm,lg", 
           "filter_type" => "new,old,used",
           "limit" => "10" }

But my approach only passes limit,

def product_params
  params.permit(:limit, /filter_.*/)
end

Solution

  • The permit method only processes an incoming value if it's a Symbol, String, or Hash.

    If you want to try to work around this you could do something like this:

    filter_names = params.keys.select { |key| key[/\Afilter_.*/] }
    params.permit(:limit, *filter_names)
    

    But be aware that the point of Strong Parameters is to define an explicit set of allowed values to avoid security problems with mass-assigning user-provided values. As long as it's always safe to allow any user to pass in any kind of filter_* value, then you should be OK.