ActionController::Parameters -> permit_recursive_params
require 'pp'
require 'active_support/core_ext/object/try'
require 'action_controller'
def permit_recursive_params(params)
(params.try(:to_unsafe_h) || params).map do |key, value|
if value.is_a?(Array)
if value.first.respond_to?(:map)
{ key => [ permit_recursive_params(value.first) ] }
else
{ key => [] }
end
elsif value.is_a?(Hash)
{ key => permit_recursive_params(value) }
else
key
end
end
end
params = ActionController::Parameters.new(
budget: {
tree: {
name: "Australia",
value: 39904,
id: 6,
description: "",
string_array: ["one", "two"],
array_with_hashes: [{
a: "1"
}, {
a: "2"
}],
type: {
name: "Other",
icon: "<i class=\"fa fa-pagelines\"></i>"
},
children: [
{
name: "Boxes",
value: 451609,
id: 7,
description: "Used to store things.",
type: {
name: "Storage",
icon: "<i class=\"fa fa-archive\"></i>"
},
children: [
{
name: "Boxes",
value: 451609,
id: 7,
description: "Used to store things.",
type: {
name: "Storage",
icon: "<i class=\"fa fa-archive\"></i>"
},
children: [
{
name: "Boxes",
value: 451609,
id: 7,
description: "Used to store things.",
type: {
name: "Storage",
icon: "<i class=\"fa fa-archive\"></i>"
}
}
]
}
]
},
{
name: "Boxes",
value: 451609,
id: 7,
description: "Used to store things.",
type: {
name: "Storage",
icon: "<i class=\"fa fa-archive\"></i>"
}
},
{
name: "Boxes",
value: 451609,
id: 7,
description: "Used to store things.",
type: {
name: "Storage",
icon: "<i class=\"fa fa-archive\"></i>"
}
}
]
}
}
)
pp params.require(:budget).permit(tree: permit_recursive_params(params[:budget][:tree])).to_h
{"tree"=>
{"name"=>"Australia",
"value"=>39904,
"id"=>6,
"description"=>"",
"string_array"=>["one", "two"],
"array_with_hashes"=>[{"a"=>"1"}, {"a"=>"2"}],
"type"=>{"name"=>"Other", "icon"=>"<i class=\"fa fa-pagelines\"></i>"},
"children"=>
[{"name"=>"Boxes",
"value"=>451609,
"id"=>7,
"description"=>"Used to store things.",
"type"=>{"name"=>"Storage", "icon"=>"<i class=\"fa fa-archive\"></i>"},
"children"=>
[{"name"=>"Boxes",
"value"=>451609,
"id"=>7,
"description"=>"Used to store things.",
"type"=>
{"name"=>"Storage", "icon"=>"<i class=\"fa fa-archive\"></i>"},
"children"=>
[{"name"=>"Boxes",
"value"=>451609,
"id"=>7,
"description"=>"Used to store things.",
"type"=>
{"name"=>"Storage",
"icon"=>"<i class=\"fa fa-archive\"></i>"}}]}]},
{"name"=>"Boxes",
"value"=>451609,
"id"=>7,
"description"=>"Used to store things.",
"type"=>{"name"=>"Storage", "icon"=>"<i class=\"fa fa-archive\"></i>"}},
{"name"=>"Boxes",
"value"=>451609,
"id"=>7,
"description"=>"Used to store things.",
"type"=>
{"name"=>"Storage", "icon"=>"<i class=\"fa fa-archive\"></i>"}}]}}