【发布时间】:2016-06-10 01:34:12
【问题描述】:
如何允许/白名单具有非常不规则(无法声明)结构的深层嵌套哈希。
例子:
{"widgets" => [
{
"id" => 75432,
"conversion_goal_id" => 1331,
"options" => {"form_settings"=>{"formbuilder-bg-color"=>"rgba(255, 255, 255, 0)", "font-size"=>"14px", "form-field-depth"=>"42px"}, "linkedWidget"=>""},
"type" => "formbuilder-widget"
},
{
"id" => 75433,
"conversion_goal_id" => nil,
"options" => {"width"=>"200px", "height"=>"185px", "display"=>"block", "left"=>313, "top"=>152, "position"=>"absolute"},
"type" => "social-sharing-widget"
},
{},
]}
所以options JSON/hash 对象没有任何指定的结构。
它是无形的。
可能是这样的
{"width"=>"200px", "height"=>"185px", "display"=>"block", "left"=>313, "top"=>152, "position"=>"absolute"}
或者:
{"form_settings"=>{"formbuilder-bg-color"=>"rgba(255, 255, 255, 0)", "font-size"=>"14px", "form-field-depth"=>"44px"},
"linkedWidget"=>"",
"required_height"=>164,
"settings"=>
[{"field_options"=>{"include_other_option"=>true, "size"=>"large", "view_label"=>false},
"field_type"=>"text",
"label"=>"Name:",
"required"=>false,
"asterisk"=>false,
"textalign"=>"left"},
{"field_options"=>{"include_other_option"=>true, "size"=>"large", "view_label"=>false},
"field_type"=>"email",
"label"=>"Email:",
"required"=>false,
"asterisk"=>false,
"textalign"=>"left"},
{"buttonalign"=>"left",
"buttonbgcolor"=>"#ba7373",
"buttonfont"=>"Old Standard TT",
"buttonfontweight"=>"bold",
"buttonfontstyle"=>"normal",
"buttonfontsize"=>"18px",
"buttonheight"=>"46px",
"buttontxtcolor"=>"#ffffff",
"field_options"=>{"include_other_option"=>true, "size"=>"large", "view_label"=>false},
"field_type"=>"button",
"label"=>"START LIVING",
"required"=>true,
"textalign"=>"left"}]}
Widgets 节点只是Array。
我没有找到任何关于如何将哈希数组中的嵌套属性列入白名单的信息。
如何做到这一点?
我在文档中找到了一些可以直接指定keys 的信息,
page_params.permit({widgets: [:key1, :key2]})
但这不起作用,因为我想允许 options 哈希中的所有属性/键。
This solution,也不支持数组,但允许将嵌套对象列入白名单:
params.require(:screenshot).permit(:title).tap do |whitelisted|
whitelisted[:assets_attributes ] = params[:screenshot][:assets_attributes ]
end
那么我如何在每个元素 options 属性(哈希数组)中加入白名单?
回复评论:
我需要允许小部件节点中
options属性中的所有内容。小部件节点位于widgets数组中。我仍然需要防止其他领域,例如link_text、'text_value' 等在数组中 - 我不希望它们被提交。我需要强大的参数来将使用的参数列入白名单,并将未使用的参数列入备用名单。有些参数只存在于前端,不存在于后端。如果我提交所有内容 - 那么我将有例外。
【问题讨论】:
-
你在用
options属性做什么?在进行批量赋值时,通常使用强参数。 -
options字段用于保存特定于给定小部件的选项。不同的小部件有不同的选项,所以它是无形的。 -
不敢相信在这个问题发布将近 4 年后,似乎仍然没有办法通过一组深度嵌套的动态哈希来实现这一点。
-
您不能在发送前在前端将选项值 JSON 化,然后在后端将
JSON.parse进行 JSON 化吗?
标签: ruby-on-rails arrays ruby hash strong-parameters