如何通过 Rails 中的强参数获取哈希属性值?
How do I get a Hash attribute value past Strong Parameters in Rails?
我正在尝试在模型中使用序列化哈希属性。我设置了表单,因此它可以正确提交数据。这是我得到的哈希值:
Parameters: {"utf8"=>"√", "authenticity_token"=>"...", "product"=>{"name"=>"h", "description"=>"", "pricing_hash"=>{"Unit"=>"0.0", "Gram"=>"10.0", "Ounce"=>"200.0"}}, "commit"=>"Create Product"}
重要的值是:pricing_hash,数据是它应该的样子。但是,当我提交时,它不会保存哈希值,我会收到控制台消息:
Unpermitted parameters: Unit, Gram, Ounce
我可以破解控制器,允许我需要的值(单位、克等),虽然我想动态地这样做,以在未来扩展定价选项,但我不知道如何形成控制器方法以允许这些参数。
您的强参数方法应如下所示:
params.require(:product).permit(:name, :description,
pricing_hash: [:Unit, :Gram, :Ounce])
我不能 100% 确定大写是否有影响。但是,散列必须位于列表的末尾。例如,您不能在此之后放置 :name
,否则会引发错误。
我正在尝试在模型中使用序列化哈希属性。我设置了表单,因此它可以正确提交数据。这是我得到的哈希值:
Parameters: {"utf8"=>"√", "authenticity_token"=>"...", "product"=>{"name"=>"h", "description"=>"", "pricing_hash"=>{"Unit"=>"0.0", "Gram"=>"10.0", "Ounce"=>"200.0"}}, "commit"=>"Create Product"}
重要的值是:pricing_hash,数据是它应该的样子。但是,当我提交时,它不会保存哈希值,我会收到控制台消息:
Unpermitted parameters: Unit, Gram, Ounce
我可以破解控制器,允许我需要的值(单位、克等),虽然我想动态地这样做,以在未来扩展定价选项,但我不知道如何形成控制器方法以允许这些参数。
您的强参数方法应如下所示:
params.require(:product).permit(:name, :description,
pricing_hash: [:Unit, :Gram, :Ounce])
我不能 100% 确定大写是否有影响。但是,散列必须位于列表的末尾。例如,您不能在此之后放置 :name
,否则会引发错误。