There may be a cleaner solution to resolve this issue, but this is my current job. The general idea is to calculate how deep my nesting is, and then automatically generate the correct nested hash based on this number. So follow your example:
def count_levels(node_params) if !node_params[:nodes].nil? max = 0 node_params[:node_parameters].each do |child_params| count = count_levels(child_params[1]) max = count if count > max end return max + 1 else return 0 end end def node_params node_attributes_base = [:id, :name] nodes = [] (1..count_levels(params[:node])).each do |val| nodes = node_attributes_base + [node_attributes: nodes] end params.require(:node).permit(:id, :name, node_attributes: nodes) end
(The above example can be cleared more, because it is based on my code, where the top level does not have the same parameters. I left it as I did since it worked on my system.)
source share