Search code examples
ruby-on-railsactioncontroller

Permit any parameter nested inside a given param


I have a list of parameters like this:

<input class="form-control" name="analysis[strengths][0]" id="swot_analysis_strengths_0" type="text">
<input class="form-control" name="analysis[strengths][1]" id="swot_analysis_strengths_1" type="text">
...
etc

Then there's also

<input class="form-control" name="analysis[weaknesses][x]" id="swot_analysis_strengths_2" type="text">
<input class="form-control" name="analysis[opportunities][x]" id="swot_analysis_strengths_2" type="text">
<input class="form-control" name="analysis[threats][x]" id="swot_analysis_strengths_2" type="text">

In my controller I have

params.require(:swot_analysis).permit(:strengths, :weaknesses, :opportunities, :threats)

That doesn't work. The only way I've got it to work so fat is by doing this

sanitized_params = params.require(:swot_analysis).permit(:strengths =>['0','1'], :weaknesses =>['0','1'], :opportunities =>['0','1'], :threats =>['0','1'])

However the number of members for each array will vary, users will be able to add and remove members as they please. So I need a method to simply permit any sub-param of the original for parameters.

Would be nice to allow it only if it's a number, but not really a priority right now


Solution

  • This should take care of the member array lengths:

    params.require(:swot_analysis).permit(:strengths =>[], :weaknesses =>[], :opportunities =>[], :threats =>[])
    

    http://api.rubyonrails.org/classes/ActionController/Parameters.html