ruby on rails - Recursive/Tree like strong parameters? -


is there way of specifying arbitrarily deep strong parameters tree structures in rails 4? example, how specify follows:

{   "node": {     "name": "parent",     "nodes": [       { "name": "child1", "nodes": []},       { "name": "child2", "nodes": [         {"name": "grandchild", "nodes": []}       ]}     ]   } } 

to allow each node have name attribute, , nodes attribute?

there may cleaner solution solving current work around. general idea count how deep nesting goes , auto generate correct nested hash based on number. follow example:

def count_levels(node_params)    if !node_params[:nodes].nil?     max = 0     node_params[:node_parameters].each |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 |val|     nodes = node_attributes_base + [node_attributes: nodes]   end   params.require(:node).permit(:id, :name, node_attributes: nodes) end 

(the above example can cleaned more since it's based on code top level did not have same parameters. left had since worked on system.)


Comments